My first suggestion is that you use a JSON
file rather than a YAML
file for configuration, since Go supports it natively; you don't need to use any external packages.
type DBConfig struct {
Path string `json:"path"`
}
func loadConfig(path string) (*DBConfig, error) {
data, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
var conf DBConfig
err = json.Unmarshal(data, &conf)
if err != nil {
return nil, err
}
return &conf, nil
}
My second suggestion is that you pass in the path to this config file in as a flag
. You can supply a flag when you run your application like this:
$ go build . -o MyApp
$ ./MyApp --config=path/to/config/file
Flags are very powerful and allow you to easily configure your applications without changing much code. Using flags in Golang is simple.
var configPath = flag.String("config", "", "Path to file containing app config")
Just make sure that you add flag.Parse
to the top of your main
function in order to access them.
Here's a full example.
Good luck!