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

运行编译的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
}

图片转代码服务由CSDN问答提供 功能建议

我使用 go build main.go 构建go文件。 但是该程序使用的是ini文件,运行 ./ main 时如何使用该文件,导致出现此错误:

   2018/09/20 17:37:38打开config / config.ini:没有这样的文件或目录
2018 / 09/20 17:37:38打开config / config.ini:没有这样的文件或目录
panic:打开配置 /config.ini:没有这样的文件或目录
 
goroutine 1 [运行中]:
log.Panic(0xc0000f7e98,0x1,0x1)
   
 
 

使用此文件的是:

  func GetConfigFile()(* ini.File,错误){
f,err:= ini.Load(“ config / config.ini”)  
 if err!= nil {
 log.Println(err)
} 
返回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

    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • doutan5844 2018-09-20 09:56

    Use absolute path like this :

    func GetConfigFile() (*ini.File, error) {
        f, err := ini.Load("/var/config/config.ini")
        if err != nil {
            log.Println(err)
        }
        return f, err
    }
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题