What is the preferred way to handle configuration parameters for a Go program?

Technology CommunityCategory: GolangWhat is the preferred way to handle configuration parameters for a Go program?
VietMX Staff asked 3 years ago

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

Consider:

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

And to read the file:

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]