Well, you can just create a config file using JSON or YAML and then read its’ contents. Let’s assume you have something like this for the config file:
{
"login": "user123",
"password": "SuperSecure"
}
You can easily use encoding/json to read it. Let’s define an app config struct to hold your config like so:
// AppConfig stores our app's configuration.
type AppConfig struct {
Login string `json:"login"`
Password string `json:"password"`
}
… 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.