Skip to content

ThomasObenaus/go-conf

Repository files navigation

go-conf - Configuration with less code

Mentioned in Awesome Go Go Reference build Go Report Card Quality Gate Status Coverage Code Smells Security Rating Maintainability Rating Reliability Rating Vulnerabilities CodeQL

Installation

go get github.com/ThomasObenaus/go-conf

What is go-conf?

go-conf is a solution for handling configurations in golang applications.

go-conf supports reading configuration parameters from multiple sources. The order they are applied is:

  1. Default values are overwritten by
  2. Parameters defined in the config-file, which are overwritten by
  3. Environment variables, which are overwritten by
  4. Command-Line parameters

The aim is to write as less code as possible:

  • No need to write code to integrate multiple libraries that support reading a configuration from file/ commandline or the environment.
  • No need to code to take the values from that library to fill it into the config struct you want to use in your app anyway.

Instead one just has to define the config structure and annotates it with struct tags.

package main

import (
    "fmt"

    config "github.com/ThomasObenaus/go-conf"
)

// Define the config struct and annotate it with the cfg tag.
type MyFontConfig struct {
    Color string `cfg:"{'name':'color','desc':'The value of the color as hexadecimal RGB string.','default':'#FFFFFF'}"`
    Name  string `cfg:"{'name':'name','desc':'Name of the font to be used.'}"`
    Size  int    `cfg:"{'name':'size','desc':'Size of the font.','short':'s'}"`
}

func main() {

    // Some command line arguments
    args := []string{
        // color not set  --> default value will be used "--color=#ff00ff",
        "--name=Arial",
        "-s=12", // use -s (short hand version) instead of --size
    }

    // 1. Create an instance of the config struct that should be filled
    cfg := MyFontConfig{}

    // 2. Create an instance of the config provider
    provider, err := config.NewConfigProvider(&cfg, "MY_APP", "MY_APP")
    if err != nil {
        panic(err)
    }

    // 3. Read the config and populate the struct
    if err := provider.ReadConfig(args); err != nil {
        panic(err)
    }

    // 4. Thats it! Now the config can be used.
    fmt.Printf("FontConfig: color=%s, name=%s, size=%d\n", cfg.Color, cfg.Name, cfg.Size)
}

Features

  • Automatically populates a struct using values given via command line
  • Read config parameters from multiple sources like command line, environment variables and config files (yaml)
  • Support of default values
  • Short hand parameters for command line flags
  • Print usage on command line
  • Custom mapping functions to support parsing of config parameters into complex structures and type conversion
  • Support of config parameter lists
  • Support of complex structs with multiple levels

License

FOSSA Status