golang中的文件路径

Cor*_*ave 4 go

我有一个具有以下结构的项目:

|_main.go
|_config
  |_config.go
  |_config_test.go
  |_config.json
Run Code Online (Sandbox Code Playgroud)

我的下一个代码行是config.go

file, _ := os.Open("config/config.json")
Run Code Online (Sandbox Code Playgroud)

当我执行包含此代码行的方法时,main.go所有代码行都在工作。但是当我尝试执行此方法时,config_test.go它会产生错误:

open config/config.json: no such file or directory
Run Code Online (Sandbox Code Playgroud)

据我了解,这是一个工作目录问题,因为我正在使用来自不同目录的相对路径启动相同的代码。如何在不使用完整路径的情况下解决此问题config.go

Mon*_*eep 5

相对路径始终根据当前目录进行解析。因此,最好避免相对路径。

使用命令行标志或配置管理工具(更好的方法),例如Viper

另外,根据十二因素应用程序,您的配置文件应该位于项目之外。

例如 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
}
Run Code Online (Sandbox Code Playgroud)