Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle configuration in Go [closed]

I'm new at Go programming, and I'm wondering: what is the preferred way to handle configuration parameters for a Go program (the kind of stuff one might use properties files or ini files for, in other contexts)?

like image 717
theglauber Avatar asked May 09 '13 15:05

theglauber


People also ask

What is config Go?

Application configuration has remained largely static for most of our lifetime, using flags, environment variables and files. Any change has usually required restarting the application or significant complexity in code to signal and reload the config.

What is Viper config?

Viper is a complete configuration solution for Go applications including 12-Factor apps. It is designed to work within an application, and can handle all types of configuration needs and formats. It supports: setting defaults. reading from JSON, TOML, YAML, HCL, envfile and Java properties config files.


2 Answers

The JSON format worked for me quite well. The standard library offers methods to write the data structure indented, so it is quite readable.

See also this golang-nuts thread.

The benefits of JSON are that it is fairly simple to parse and human readable/editable while offering semantics for lists and mappings (which can become quite handy), which is not the case with many ini-type config parsers.

Example usage:

conf.json:

{     "Users": ["UserA","UserB"],     "Groups": ["GroupA"] } 

Program to read the configuration

import (     "encoding/json"     "os"     "fmt" )  type Configuration struct {     Users    []string     Groups   []string }  file, _ := os.Open("conf.json") defer file.Close() decoder := json.NewDecoder(file) configuration := Configuration{} err := decoder.Decode(&configuration) if err != nil {   fmt.Println("error:", err) } fmt.Println(configuration.Users) // output: [UserA, UserB] 
like image 85
nemo Avatar answered Oct 09 '22 10:10

nemo


Another option is to use TOML, which is an INI-like format created by Tom Preston-Werner. I built a Go parser for it that is extensively tested. You can use it like other options proposed here. For example, if you have this TOML data in something.toml

Age = 198 Cats = [ "Cauchy", "Plato" ] Pi = 3.14 Perfection = [ 6, 28, 496, 8128 ] DOB = 1987-07-05T05:45:00Z 

Then you can load it into your Go program with something like

type Config struct {     Age int     Cats []string     Pi float64     Perfection []int     DOB time.Time }  var conf Config if _, err := toml.DecodeFile("something.toml", &conf); err != nil {     // handle error } 
like image 26
BurntSushi5 Avatar answered Oct 09 '22 10:10

BurntSushi5