config

package
v0.3.6 Latest Latest
Warning

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

Go to latest
Published: Apr 24, 2024 License: Apache-2.0 Imports: 11 Imported by: 10

README

config

This package is an wrapper over viper with opinionated defaults that allows loading config from a yaml file and environment variables.

Usage

package main

import (
	"encoding/json"
	"fmt"

	"github.com/goto/salt/config"
)

type Config struct {
	Port     int            `mapstructure:"port" default:"8080"`
	DB       DBConfig       `mapstructure:"db"`
	NewRelic NewRelicConfig `mapstructure:"new_relic"`
	LogLevel string         `mapstructure:"log_level" default:"info"`
}

type DBConfig struct {
	Port int    `mapstructure:"port" default:"5432"`
	Host string `mapstructure:"host" default:"localhost"`
}

type NewRelicConfig struct {
	Enabled bool   `mapstructure:"enabled" default:"false"`
	AppName string `mapstructure:"app_name" default:"test-app"`
	License string `mapstructure:"license"`
}

func main() {
	var c Config
	l := config.NewLoader(
		// config.WithViper(viper.New()), // default
		// config.WithName("config"), // default
		// config.WithType("yaml"), // default
		// config.WithEnvKeyReplacer(".", "_"), // default
		config.WithPath("$HOME/.test"),
		config.WithEnvPrefix("CONFIG"),
	)

	if err := l.Load(&c); err != nil { // pass pointer to the struct into which you want to load config
		panic(err)
	}
	s, _ := json.MarshalIndent(c, "", "  ") // spaces: 2 | tabs: 1 😛
	fmt.Println(string(s))
}

In the above program a YAML file or environment variables can be used to configure.

port: 9000
db:
    port: 5432
    host: db-host-yaml
new_relic:
    enabled: true
    app_name: config-test-yaml
    license: ____LICENSE_STRING_OF_40_CHARACTERS_____
log_level: debug

or

export CONFIG_PORT=9001
export CONFIG_DB_PORT=5432
export CONFIG_DB_HOST=db-host-env
export CONFIG_NEW_RELIC_ENABLED=true
export CONFIG_NEW_RELIC_APP_NAME=config-test-env
export CONFIG_NEW_RELIC_LICENSE=____LICENSE_STRING_OF_40_CHARACTERS_____
export CONFIG_LOG_LEVEL=debug

or a mix of both.

Configs set in environment will override the ones set as default and in yaml file.

TODO

  • function to print/return config keys in yaml path and env format with defaults as helper
  • add support for flags

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func StringToJsonFunc

func StringToJsonFunc() mapstructure.DecodeHookFunc

StringToJsonFunc is a mapstructure.DecodeHookFunc that converts a string to a interface{} if the string is valid json. This is useful for unmarshaling json strings into a map. For example, if you have a struct with a field of type map[string]string like labels or annotations,

Types

type ConfigFileNotFoundError

type ConfigFileNotFoundError struct {
	// contains filtered or unexported fields
}

ConfigFileNotFoundError is returned when the config file is not found Viper will load from env or defaults

func (ConfigFileNotFoundError) Error

func (err ConfigFileNotFoundError) Error() string

func (*ConfigFileNotFoundError) Unwrap

func (err *ConfigFileNotFoundError) Unwrap() error

type Loader

type Loader struct {
	// contains filtered or unexported fields
}

func NewLoader

func NewLoader(options ...LoaderOption) *Loader

NewLoader returns a config loader with given LoaderOption(s)

func (*Loader) Load

func (l *Loader) Load(config interface{}) error

Load loads configuration into the given mapstructure (https://github.com/mitchellh/mapstructure) from a config.yaml file and overrides with any values set in env variables

type LoaderOption

type LoaderOption func(*Loader)

func WithBindPFlags

func WithBindPFlags(pfs *pflag.FlagSet, cfg interface{}) LoaderOption

WithBindPFlags binds viper to pflags based on the tags in the struct. Use tag `cmdx` to bind struct field to cli flag. e.g.

type Config struct {
	Host string `yaml:"host" cmdx:"host"`
}

func WithDecoderConfigOption

func WithDecoderConfigOption(opts ...viper.DecoderConfigOption) LoaderOption

WithDecoderConfigOption sets the decoder config options for viper. See https://pkg.go.dev/github.com/mitchellh/mapstructure#DecoderConfig for more details

func WithEnvKeyReplacer

func WithEnvKeyReplacer(old string, new string) LoaderOption

WithEnvKeyReplacer sets the `old` string to be replaced with the `new` string environmental variable to a key that does not match it.

func WithEnvPrefix

func WithEnvPrefix(in string) LoaderOption

WithEnvPrefix sets the prefix for keys when checking for configs in environment variables. Internally concatenates with keys with `_` in between

func WithFile

func WithFile(file string) LoaderOption

WithFile explicitly defines the path, name and extension of the config file

func WithName

func WithName(in string) LoaderOption

WithName sets the file name of the config file without the extension

func WithPath

func WithPath(in string) LoaderOption

WithPath adds config path to search the config file in, can be used multiple times to add multiple paths to search

func WithType

func WithType(in string) LoaderOption

WithType sets the type of the configuration e.g. "json", "yaml", "hcl" Also used for the extension of the file

func WithViper

func WithViper(in *viper.Viper) LoaderOption

WithViper sets the given viper instance for loading configs instead of the default configured one

Jump to

Keyboard shortcuts

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