doutao1171
2018-09-20 09:46
浏览 769
已采纳

运行编译的golang程序时如何使用配置文件

I build a go file using go build main.go. But this program is using a ini file, how do I use this file cause when I run ./main, I am getting this error:

2018/09/20 17:37:38 open config/config.ini: no such file or directory
2018/09/20 17:37:38 open config/config.ini: no such file or directory
panic: open config/config.ini: no such file or directory

goroutine 1 [running]:
log.Panic(0xc0000f7e98, 0x1, 0x1)

The code for using this file are:

func GetConfigFile() (*ini.File, error) {
    f, err := ini.Load("config/config.ini")
    if err != nil {
        log.Println(err)
    }
    return f, err
}
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

2条回答 默认 最新

  • dsjk3214 2018-09-20 18:40
    最佳回答

    It depends on where you run your program from. Read up on the concept of the current working directory, if you run your program from a console, the path is usually displayed at the start of the line. You use the relative path "config/config.ini" in your code which means that if you are currently in the directory /home/user then the file is expected to be at /home/user/config/config.ini.

    You may want to either run your code from a different directory or use an absolute path in your code, e.g. /home/user/go/src/myapp/config/config.ini

    评论
    解决 无用
    打赏 举报
查看更多回答(1条)

相关推荐 更多相似问题