duanba4942 2016-04-05 08:22
浏览 71
已采纳

Golang中的文件路径

I have a project with next structure:

|_main.go
|_config
  |_config.go
  |_config_test.go
  |_config.json

I'm having next code line in config.go:

file, _ := os.Open("config/config.json")

When I'm executing method contained this code line from main.go all is working. But when I'm trying to execute this method from config_test.go it produces error:

open config/config.json: no such file or directory

As I understood it is a working directory issue because I'm launching same code with relative path from different directories. How can I fix this problem without using full path in config.go?

  • 写回答

1条回答 默认 最新

  • douzhizao0270 2016-04-05 09:54
    关注

    Relative paths are always resolved basis your current directory. Hence it's better to avoid relative paths.

    Use command line flags or a configuration management tool (better approach) like Viper

    Also according to The Twelve-Factor App your config files should be outside your project.

    Eg usage with 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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥20 求用stm32f103c6t6在lcd1206上显示Door is open和password:
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法