Configuration in Golang
Configuration can sometimes be difficult. Pulling variables outside your source that change based on environment or other external services is very important to maintaining your application. Many people use YAML or config files in the native language. When dealing with configuration using Golang, I’ve always defaulted to using JSON. Partly because it is so easy to ready, but also because it is very portable. Almost any external service or configuration management system (Chef or Ansible) can parse and create JSON.
We will start with a simple JSON file that has nested objects.
After creating the JSON file, you can map it to a struct. You could also create the struct first and the JSON second. It’s up to you how you do it.
You will notice the difference in each of the fields’ tags. When the JSON key and the struct keys do not match, you can map them using
json:"json_key". You can also ignore fields (which is especially helpful when writing out JSON) by doing
Marshalling (or Loading the Config)
Once you’ve create the struct and setup the JSON configuration file, you’re ready to load the data. Loading the configuration is as easy as reading the file from disk and marshalling it into your object.
You can simply use this function in your Go program like so:
Hope this helps. Enjoy!