简体   繁体   中英

File path in golang

I have a project with next structure:

|_main.go
|_config
  |_config.go
  |_config_test.go
  |_config.json

I'm having next code line in config.go :

file, _ := os.Open("config/config.json")

When I'm executing method contained this code line from main.go all is working. But when I'm trying to execute this method from config_test.go it produces error:

open config/config.json: no such file or directory

As I understood it is a working directory issue because I'm launching same code with relative path from different directories. How can I fix this problem without using full path in config.go ?

Relative paths are always resolved basis your current directory. Hence it's better to avoid relative paths.

Use command line flags or a configuration management tool (better approach) like Viper

Also according to The Twelve-Factor App your config files should be outside your project.

Eg usage with 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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM