-3

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
}
yong ho
  • 3,892
  • 9
  • 40
  • 81
  • 2
    Obviously `config/config.ini` doesn't exist, relative to the path from where you're running your program. Remember, relative paths are relative to the current *working directory*, not the application binary. – Jonathon Reinhart Sep 20 '18 at 09:53
  • Make sure you use the proper path when opening your config file. You use relative path, which is always resolved to the working directory, which is the current folder when run via `go run`, which is different than the compiled binary's folder. See possible duplicate [how to reference a relative file from code and tests](https://stackoverflow.com/questions/31059023/how-to-reference-a-relative-file-from-code-and-tests/31059125#31059125). – icza Sep 20 '18 at 09:56

2 Answers2

0

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
}
0

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

gonutz
  • 5,087
  • 3
  • 22
  • 40