liveBook · Manning

Configuration

As explained in Go in Practice, Second Edition

Configuration is information that specifies how a program or system should operate.

Configuration supplies values that can change without changing application code. Command-line options suit values chosen for a particular run; a file is a better fit for persistent, potentially complex settings that would otherwise need to be retyped. Environment variables are another way to provide configuration, particularly for 12-factor applications. section 2.2 section 2.2.1

Choose a format, then load its values at startup:

  • JSON: define a Go struct matching the file’s names and nesting, open the file, and decode it with encoding/json. Export struct fields by capitalizing their names so the decoder can populate them; check file and decoding errors. section 2.2.1
  • YAML: use github.com/kylelemons/go-gypsy/yaml to read a file and retrieve values such as a path and a Boolean enabled setting. section 2.2.1
  • INI: use github.com/go-ini/ini to load a file and read keys from a named section, converting values to the types the application needs. section 2.2.1
Listing 2.9 Parsing a JSON configuration file: json_config.go
package main

import (
     "encoding/json"
     "fmt"
     "os"
)
type configuration struct {     #1
     Enabled bool               #1
     Path    string             #1
}                               #1
func main() {
     file, err := os.Open("config.json")     #2
     if err != nil {
         panic(err)
     }
     defer file.Close()
     decoder := json.NewDecoder(file)      #3
     conf := configuration{}               #3
     err = decoder.Decode(&conf)           #3
     if err != nil {
            fmt.Println("Error:", err)
     }
     fmt.Println(conf.Path)
}

The JSON parser shows the complete path from config.json to a Go struct: open the file, defer its closure, decode into the struct, and use a loaded field. section 2.2.1

Configuration can also select resources for a deployment. When web assets are served separately—such as from a CDN—give each development, testing, and production environment its own asset location. Pass that location into the application and use it in the page template. A startup argument is one option; configuration files or a shared configuration service are others. section 10.1.4

Listing 10.7 Passing a URL location to a template
var t *template.Template
var l = flag.String("location", 
"http://localhost:8080", "A location.")           #1
var tpl = `<!DOCTYPE HTML>
<html>
  <head>
    <meta charset="utf-8">
    <title>A Demo</title>
    <link rel="stylesheet" href="{{.Location}}/styles.
    css">                                              #2
  </head>
  <body>
    <p>A demo.</p>
  </body>
</html>`
func servePage(res http.ResponseWriter, 
req *http.Request) {                            #3
     data := struct{ Location *string }{        #3
          Location: l,                          #3
     }                                          #3
     t.Execute(res, data)                       #3
}                                               #3

The template example takes an asset location from a flag and places it in the stylesheet URL, showing how an execution-time value reaches the rendered page. section 10.1.4

How Go in Practice, Second Edition covers it

How deep it goes
Works through file parsers and template wiring, while deferring detailed JSON behavior.
Examples
Uses JSON, YAML, and INI files plus a flag-driven stylesheet URL in a web template.
What it assumes
Introduces JSON struct mapping and decoding through Go code, without teaching Go syntax from zero.
What you can do after
Operate/configure it by loading file settings and supplying a deployment-specific asset location to a template.
How it connects
Connects command-line arguments, JSON, YAML, INI, templates, and CDNs.

Also explained in

Compare how 23 books explain configuration →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go in Practice, Second Edition. The section links point to the parts of the book it draws on.