config

package
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Nov 30, 2021 License: MIT Imports: 8 Imported by: 3

Documentation

Overview

Package config helps you with reading configuration from files and environment variables in a unified way. This package is used throughout Wharf to read configurations.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Builder

type Builder interface {
	// AddConfigYAMLFile appends the path of a YAML file to the list of sources
	// for this configuration.
	//
	// Later added config sources will merge on top of the previous on a
	// per config field basis. Later added sources will override earlier added
	// sources.
	AddConfigYAMLFile(path string)

	// AddConfigYAML appends a byte reader for UTF-8 and YAML formatted content.
	// Useful for reading from embedded files, database stored configs, and from
	// HTTP response bodies.
	//
	// Later added config sources will merge on top of the previous on a
	// per config field basis. Later added sources will override earlier added
	// sources.
	AddConfigYAML(reader io.Reader)

	// AddEnvironmentVariables appends an environment variable source.
	//
	// Later added config sources will merge on top of the previous on a
	// per config field basis. Later added sources will override earlier added
	// sources.
	//
	// However, multiple environment variable sources cannot be added, due to
	// technical limitations with the implementation. Even if they use different
	// prefixes.
	//
	// Environment variables must be in all uppercase letters, and nested
	// structs use a single underscore "_" as delimiter. Example:
	//
	//  c := config.NewBuilder(myConfigDefaults)
	//  c.AddEnvironmentVariables("FOO")
	//
	//  type MyConfig struct {
	//  	Bar        string // set via "FOO_BAR"
	//  	LoremIpsum string // set via "FOO_LOREMIPSUM"
	//  	Hello      struct {
	//  		World string // set via "FOO_HELLO_WORLD"
	//  	}
	//  }
	//
	// The prefix shall be without a trailing underscore "_" as this package
	// adds that in by itself. To not use a prefix, pass in an empty string as
	// prefix instead.
	AddEnvironmentVariables(prefix string)

	// Unmarshal applies the configuration, based on the numerous added sources,
	// on to an existing struct.
	//
	// For any field of type pointer and is set to nil, this function will
	// create a new instance and assign that before populating that branch.
	//
	// If none of the Builder.Add...() functions has been called before
	// this function, then this function will effectively only apply the default
	// configuration onto this new object.
	//
	// The error that is returned is caused by any of the added config sources,
	// such as from invalid YAML syntax in an added YAML file.
	Unmarshal(config interface{}) error
}

Builder type has methods for registering configuration sources, and then using those sources you can unmarshal into a struct to read the configuration.

Later added config sources will merge on top of the previous on a per config field basis. Later added sources will override earlier added sources.

func NewBuilder

func NewBuilder(defaultConfig interface{}) Builder

NewBuilder creates a new Builder based on a default configuration.

Due to technical limitations, it's vital that this default configuration is of the same type that the config that you wish to unmarshal later, or at least that it contains fields with the same names.

Example
package main

import (
	"bytes"
	_ "embed"
	"fmt"
	"os"

	"github.com/iver-wharf/wharf-core/pkg/config"
)

type Logging struct {
	LogLevel string
}

type DBConfig struct {
	Host string
	Port int
}

type Config struct {
	// Both mapstructure:",squash" and yaml:",inline" needs to be set in
	// embedded structs, even if you're only reading environment variables
	Logging  `mapstructure:",squash" yaml:",inline"`
	Username string
	Password string
	DB       DBConfig
}

var defaultConfig = Config{
	Logging: Logging{
		LogLevel: "Warning",
	},
	Username: "postgres",
	DB: DBConfig{
		Host: "localhost",
		Port: 5432,
	},
}

//go:embed testdata/embedded-config.yml
var embeddedConfig []byte

func main() {
	cfgBuilder := config.NewBuilder(defaultConfig)
	cfgBuilder.AddConfigYAML(bytes.NewReader(embeddedConfig))
	cfgBuilder.AddConfigYAMLFile("/etc/my-app/config.yml")
	cfgBuilder.AddConfigYAMLFile("$HOME/.config/my-app/config.yml")
	cfgBuilder.AddConfigYAMLFile("my-app-config.yml") // from working directory
	cfgBuilder.AddEnvironmentVariables("MYAPP")

	os.Setenv("MYAPP_PASSWORD", "Sommar2020")

	var cfg Config
	if err := cfgBuilder.Unmarshal(&cfg); err != nil {
		fmt.Println("Failed to read config:", err)
		return
	}

	fmt.Println("Log level:", cfg.LogLevel) // set from embeddedConfig
	fmt.Println("Username: ", cfg.Username) // uses defaultConfig.Username
	fmt.Println("Password: ", cfg.Password) // set from environment variable
	fmt.Println("DB host:  ", cfg.DB.Host)  // uses defaultConfig.DB.Host
	fmt.Println("DB port:  ", cfg.DB.Port)  // set from embeddedConfig

}
Output:

Log level: Info
Username:  postgres
Password:  Sommar2020
DB host:   localhost
DB port:   8080

Jump to

Keyboard shortcuts

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