Help us shape the future of Go! Take the 2026 Go Developer Survey

config

package module
v1.1.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 21, 2018 License: BSD-3-Clause Imports: 12 Imported by: 0

README

Documentation

Overview

Package config is an ergonomic configuration parsing toolkit. The schema is declared using a struct type, and values can be read from YAML files or set via command-line flags.

A pointer to a preallocated configuration object of a user-defined struct type must be passed to all functions. The type can have an arbitrary number of nested structs (either embedded or through an initialized pointer). Only exported fields can be used. The object can be initialized with default values.

The field names are spelled in lower case in YAML files and on the command-line. The accessor functions and flag values use dotted paths to identify the field, such as "audio.samplerate".

Supported field types are bool, int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, float32, float64, string, []string, and time.Duration.

The Get method is provided for completeness; the intended way to access configuration values is through direct struct field access.

Short example:

c := &myConfig{}

flag.Usage = config.FlagUsage(c)
flag.Var(config.FileReader(c), "f", "read config from YAML files")
flag.Var(config.Assigner(c), "c", "set config keys (path.to.key=value)")
flag.Parse()

Longer example:

package main

import (
	"flag"
	"fmt"
	"log"

	"github.com/tsavola/config"
)

type myConfig struct {
	Comment string

	Size struct {
		Width  uint32
		Height uint32
	}

	Audio struct {
		Enabled    bool
		SampleRate int
	}
}

func main() {
	c := new(myConfig)
	c.Size.Width = 640
	c.Size.Height = 480
	c.Audio.SampleRate = 44100

	if err := config.ReadFileIfExists("defaults.yaml", c); err != nil {
		log.Print(err)
	}

	if x, _ := config.Get(c, "audio.samplerate"); x.(int) <= 0 {
		config.MustSet(c, "audio.enabled", false)
	}

	dump := flag.Bool("dump", false, "create defaults.yaml")
	flag.Var(config.FileReader(c), "f", "read config from YAML files")
	flag.Var(config.Assigner(c), "c", "set config keys (path.to.key=value)")
	flag.Usage = config.FlagUsage(c)
	flag.Parse()

	if *dump {
		if err := config.WriteFile("defaults.yaml", c); err != nil {
			log.Fatal(err)
		}
	}

	fmt.Printf("Comment is %q\n", c.Comment)
	fmt.Printf("Size is %dx%d\n", c.Size.Width, c.Size.Height)
	if c.Audio.Enabled {
		fmt.Printf("Sample rate is %d\n", c.Audio.SampleRate)
	}
}

Example usage output:

$ example -help
Usage of example:
  -c value
    	set config keys (path.to.key=value)
  -dump
    	create defaults.yaml
  -f value
    	read config from YAML files

Configuration settings:
  comment string
  size.width uint32
  size.height uint32
  audio.enabled bool
  audio.samplerate int

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Assign

func Assign(config interface{}, expr string) (err error)

Assign a value to a field of the configuration object. The field's path and string representation are parsed from an expression of the form "path=repr".

See SetFromString for parsing rules.

func Assigner

func Assigner(config interface{}) flag.Value

Assigner makes a “dynamic value” which sets fields in the configuration as it receives assignment expressions.

func FileReader

func FileReader(config interface{}) flag.Value

FileReader makes a “dynamic value” which reads files into the configuration as it receives filenames.

func FlagUsage

func FlagUsage(config interface{}) func()

FlagUsage creates a function which may be used as flag.Usage. It includes the default usage and the configuration settings.

func Get

func Get(config interface{}, path string) (value interface{}, err error)

Get the value of a field of the configuration object.

func MustAssign

func MustAssign(config interface{}, expr string)

Assign a value to a field of the configuration object. The field's path and string representation are parsed from an expression of the form "path=repr". Panic if the field doesn't exist or parsing fails.

See SetFromString for parsing rules.

func MustSet

func MustSet(config interface{}, path string, value interface{})

MustSet a field of the configuration object. The value must have the same type as the field. Panic if the field doesn't exist or the types don't match.

func MustSetFromString

func MustSetFromString(config interface{}, path string, repr string)

MustSetFromString sets a field of the configuration object. The value representation is parsed according to the type of the field. Panic if the field doesn't exist or parsing fails.

See SetFromString for parsing rules.

func PrintSettings

func PrintSettings(w io.Writer, config interface{})

PrintSettings of the given configuration. Writer defaults to the default flag set's output.

func Read

func Read(r io.Reader, config interface{}) error

Read YAML into the configuration.

func ReadFile

func ReadFile(filename string, config interface{}) (err error)

Read a YAML file into the configuration.

func ReadFileIfExists

func ReadFileIfExists(filename string, config interface{}) (err error)

Read a YAML file into the configuration. No error is returned if the file doesn't exist.

func Set

func Set(config interface{}, path string, value interface{}) (err error)

Set a field of the configuration object. The value must have the same type as the field.

func SetFromString

func SetFromString(config interface{}, path string, repr string) (err error)

SetFromString sets a field of the configuration object. The value representation is parsed according to the type of the field.

Valid boolean representations are "true", "false", "yes", "no", "y", "n", "on", and "off".

If the representation of a string list is the empty string, the field will be an empty list. If the representation starts with "[", it is assumed to be a JSON-encoded string array. Otherwise the length will be one, and repr will be the single item.

func Write

func Write(w io.Writer, config interface{}) error

Write the configuration as YAML.

func WriteFile

func WriteFile(filename string, config interface{}) (err error)

Write the configuration to a YAML file.

Types

type Setting

type Setting struct {
	Path    string
	Type    reflect.Type
	Default string
}

Setting documents a settable configuration path.

func Settings

func Settings(config interface{}) []Setting

Settings lists the settable configuration paths.

func (Setting) String

func (s Setting) String() string

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL