I am new to go programming and would like to outsource the authentication against a RESTapi into a configfile.
Can anyone help me how best to implement something like this ? It is about basic auth in the first step. But the credentials should not be in the actual code.
I have already read something that this would be possible with a yaml or a json.
… and then read it using something along these lines:
// readConfigFile reads config file and will log.Fatal if there is a
// problem opening the file (under the assumption that if we fail to
// initialize, the app literally can't run).
func readConfigFile(configPath string) AppConfig {
var config AppConfig
f, err := os.Open(configPath)
if err != nil {
// As an alternative here, you could return the error
// and have the caller be responsible for dealing with it.
log.Fatalf("Can't open config file %v.", configPath)
}
defer f.Close()
json.NewDecoder(f).Decode(&config)
return config
}
… and to use it you can obviously do something like this:
myConfig := readConfigFile("myconfig.json")
// Do something with your configuration
There are ways to make this better, but this should get you well on your way.