go - golang中的文件路径

标签 go

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

|_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/

相关文章:

linux - 执行并发 os/exec.Command.Wait() 时发生内存泄漏

go - Go 中的独占锁定

go - 如何在Go中手动代理应用程序/八位字节流(实时视频)?

go - configmaps 更新时如何在 kubernetes 的应用程序中获取通知

去构建错误 : no non-test Go files in <dir>

algorithm - Go 程序不显示分配给变量的 Sliced Int 的期望结果

go - 如何在 Go lang 中获取 ajax 发布请求值?

unit-testing - 我如何对文本将出现在屏幕中央进行单元测试?

for-loop - Golang 中的事件驱动模型

go - 清理临时文件的最佳方法