How to you handle application configuration?

Hey all,

As a hobby developer I’m limited to my own imagination when it comes to writing code, and I realise I dont always do things the best way. I’m currently looking at how my application gets its configuration and have 2 ideas so far; global or pass the config around.

I’m keen to hear what your thoughts on each are, and what you do personally.

At the moment I have the global implementation which looks like:

https://play.golang.org/p/nRFBPnb3KR

I am no expert, but I would make it global.
And then unmarshal the config from a simple JSON file, in a init() method.

No external dependencies, simple and clean.
It even supports nested configurations.

ioutil.ReadFile(…)
json.Unmarshal(…)

JSON file example:

{
   "Server": {
      "Port": 80,
      "Hostname": "localhost"
   }
}

Great example: http://goinbigdata.com/persisting-application-configuration-in-golang

If you’ve only got a couple of configuration parameters, environment variables work. But if there’s much more than that JSON or YAML configuration files are pretty much standard. If you use JSON files, there’s github.com/clbanning/checkjson#Validate to see if there are typos in the config file keys.

I have implemented the dotenv tool by Joho which works well. After re-reading my op, I think what I really meant to ask was how should I manage configuration scope.

For now I have gone with a global object, but I’m haunted by voices saying global is bad. It doesn’t seem right that a function depends on an external entity, which isn’t clearly defined in its signature. Equally, rewriting everything to take a config object also feels pretty horrific.

Hi Sion:

That particular problem is on every app developers todo list. Big dev orgs will have a reusable solution, and fortunately, the Golang community has one too: it is called Viper.

Its basic architecture is that it consolidates all configuration information, regardless of origin (command line, config files, env vars, etc.) into a single data structure that your program can query. Viper is the right way to solve this problem.

Hope that helps.

1 Like

Thank you @Ravenwater for sharing. This looks useful, but I’m failing to see what it gives me over and above what I get with dotenv. I will give it a go tonight and see how it stacks up.

Hi Sion: yep, the best way is to dive in. But as I indicated, Viper
consolidates ALL the vehicles where application configuration can come
from, not just ENV, so it solves the problem of application configuration
information consolidation much more thoroughly than dotenv.

Dr. E. Theodore L. Omtzigt
CEO and Founder
Stillwater Supercomputing, Inc.
East Coast Office : (617) 314 6424
West Coast Office: (415) 738 7387
Mobile phone # : (916) 296-7901
3941 Park Drive, Suite 20-354
El Dorado Hills, CA 95762

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.