我有一个具有下一个结构的项目:
|_main.go
|_config
|_config.go
|_config_test.go
|_config.json
我在 config.go
中有下一行代码:
file, _ := os.Open("config/config.json")
当我执行包含 main.go
中的代码行的方法时,一切正常。但是当我尝试从 config_test.go
执行此方法时,它会产生错误:
open config/config.json: no such file or directory
据我所知,这是一个工作目录问题,因为我正在使用来自不同目录的相对路径启动相同的代码。如何在不使用 config.go
中的完整路径的情况下解决此问题?
最佳答案
相对路径始终根据您当前的目录进行解析。因此最好避免相对路径。
使用命令行 flags或类似 Viper 的配置管理工具(更好的方法)
同样根据The Twelve-Factor App你的配置文件应该在你的项目之外。
例如 Viper 的用法:
import "github.com/spf13/viper"
func init() {
viper.SetConfigName("config")
// Config files are stored here; multiple locations can be added
viper.AddConfigPath("$HOME/configs")
errViper := viper.ReadInConfig()
if errViper != nil {
panic(errViper)
}
// Get values from config.json
val := viper.GetString("some_key")
// Use the value
}
关于go - golang中的文件路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36420863/