将配置文件与已编译的Go程序一起使用 [英] Using a configuration file with a compiled Go program

查看:817
本文介绍了将配置文件与已编译的Go程序一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用config.json文件的Go应用程序,以获取一些信息.当执行go run main.go时,它可以工作,但是当我将应用程序编译成可执行文件时,出现错误open config.json: no such file or directory.

I have a Go application using a config.json file to get some information. When doing a go run main.go it works but when I'm compiling the application into an executable I have the error open config.json: no such file or directory.

我的代码是:

func main() {
        data, err := ioutil.ReadFile("./config.json")
        check(err)

        var config config
        err = json.Unmarshal(data, &config)
        check(err)
}

我也尝试过ioutil.ReadFile("config.json"),它不起作用. check(err)config结构在main.go中,问题不出在这里.

I also have tried ioutil.ReadFile("config.json") and it does not work. check(err) and the config structure are in the main.go, the problem does not come from here.

main.goconfig.json和可执行文件位于同一目录中.

main.go, config.json and the executable are in the same directory.

程序编译后如何使用config.json文件?

What should I do to be able to use the config.json file once the program is compiled?

推荐答案

您的配置文件可能不在启动应用程序的工作目录中. 但是,对文件的路径进行硬编码并不是最佳实践.

Your config file is probably not in the working directory you have started your application in. But hardcoding the path to the file is not the best of practices.

使用 flag 软件包将路径作为命令行传递到配置文件标记:

Use the flag package to pass the path to your config file as a command-line flag:

var filename = flag.String("config", "config.json", "Location of the config file.")

func main() {
        flag.Parse()
        data, err := ioutil.ReadFile(*filename)
        check(err)

        var config config
        err = json.Unmarshal(data, &config)
        check(err)
}

使用./application -config=/path/to/config.json启动应用程序(取决于您的平台).

Start the application with ./application -config=/path/to/config.json (depends on your platform).

使用 os 包从系统环境中读取路径.

Use the os package to read the path from your system environment.

func main() {
        filename := os.Getenv("PATH_TO_CONFIG")
        if filename == "" {
          filename = "config.json"
        }

        data, err := ioutil.ReadFile(filename)
        check(err)

        var config config
        err = json.Unmarshal(data, &config)
        check(err)
}

设置环境变量export PATH_TO_CONFIG=/path/to/config.json(取决于您的平台)并启动应用程序.

Set the environment variable export PATH_TO_CONFIG=/path/to/config.json (depends on your platform) and start the application.

如果未向应用程序提供路径,则这两种方法都将尝试在工作目录中找到config.json.

Both approaches will attempt to find config.json in the working directory if no path was provided to the application.

这篇关于将配置文件与已编译的Go程序一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆