aconfig

package module
v0.14.4 Latest Latest
Warning

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

Go to latest
Published: May 12, 2021 License: MIT Imports: 10 Imported by: 1

README

aconfig

build-img pkg-img reportcard-img coverage-img

Simple, useful and opinionated config loader.

Rationale

There are many solutions regarding configuration loading in Go. I was looking for a simple loader that will as much as possible and be easy to use and understand. The goal was to load config from 4 places: defaults (in the code), files, environment variables, command-line flags. This library works with all of this sources.

Features

  • Simple API.
  • Clean and tested code.
  • Automatic fields mapping.
  • Supports different sources:
    • defaults in the code
    • files (JSON, YAML, TOML, DotENV, HCL)
    • environment variables
    • command-line flags
  • Dependency-free (file parsers are optional).
  • Ability to walk over configuration fields.

Install

Go version 1.14+

go get github.com/avast/aconfig

Example

type MyConfig struct {
	Port int `default:"1111" usage:"just give a number"`
	Auth struct {
		User string `default:"def-user"`
		Pass string `default:"def-pass"`
	}
	Pass string `default:"" env:"SECRET" flag:"sec_ret"`
}

var cfg MyConfig
loader := aconfig.LoaderFor(&cfg, aconfig.Config{
	// feel free to skip some steps :)
	// SkipDefaults: true,
	// SkipFiles:    true,
	// SkipEnv:      true,
	// SkipFlags:    true,
	EnvPrefix:       "APP",
	FlagPrefix:      "app",
	Files:           []string{"/var/opt/myapp/config.json", "ouch.yaml"},
	FileDecoders: map[string]aconfig.FileDecoder{
		// from `aconfigyaml` submodule
		// see submodules in repo for more formats
		".yaml": aconfigyaml.New(),
	},
})

// IMPORTANT: define your own flags with `flagSet`
flagSet := loader.Flags()

if err := loader.Load(); err != nil {
	panic(err)
}

// configuration fields will be loaded from (in order):
//
// 1. defaults set in structure tags (see MyConfig defenition)
// 2. loaded from files `file.json` if not `ouch.yaml` will be used
// 3. from corresponding environment variables with the prefix `APP_`
// 4. command-line flags with the prefix `app.` if they are

Also see examples: examples_test.go.

Integration with spf13/cobra playground.

Documentation

See these docs.

License

MIT License.

Documentation

Overview

Package aconfig provides simple but still powerful config loader.

It can read configuration from different sources, like defaults, files, environment variables, console flag parameters.

Defaults are defined in structure tags (`default` tag). For files JSON, YAML, TOML and .Env are supported.

Environment variables and flag parameters can have an optional prefix to separate them from other entries.

Also, aconfig is dependency-free, file decoders are used as separate modules (submodules to be exact) and are added to your go.mod only when used.

Loader configuration (`Config` type) has different ways to configure loader, to skip some sources, define prefixes, fail on unknown params.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config struct {
	SkipDefaults bool // SkipDefaults set to true will not load config from 'default' tag.
	SkipFiles    bool // SkipFiles set to true will not load config from files.
	SkipEnv      bool // SkipEnv set to true will not load config from environment variables.
	SkipFlags    bool // SkipFlags set to true will not load config from flag parameters.

	EnvPrefix  string // EnvPrefix for environment variables.
	FlagPrefix string // FlagPrefix for flag parameters.

	FlagDelimiter string // FlagDelimiter for flag parameters. If not set - default is ".".

	// AllFieldsRequired set to true will fail config loading if one of the fields was not set.
	// File, environment, flag must provide a value for the field.
	// If default is set and this option is enabled (or required tag is set) there will be an error.
	AllFieldRequired bool

	// AllowUnknownFields set to true will not fail on unknown fields in files.
	AllowUnknownFields bool

	// AllowUnknownEnvs set to true will not fail on unknown environment variables ().
	// When false error is returned only when EnvPrefix isn't empty.
	AllowUnknownEnvs bool

	// AllowUnknownFlags set to true will not fail on unknown flag parameters ().
	// When false error is returned only when FlagPrefix isn't empty.
	AllowUnknownFlags bool

	// DontGenerateTags disables tag generation for JSON, YAML, TOML file formats.
	DontGenerateTags bool

	// FailOnFileNotFound will stop Loader on a first not found file from Files field in this structure.
	FailOnFileNotFound bool

	// MergeFiles set to true will collect all the entries from all the given files.
	// Easy wat to cobine base.yaml with prod.yaml
	MergeFiles bool

	// FileFlag to make easier pass file with a config via flags.
	FileFlag string

	// Files from which config should be loaded.
	Files []string

	// Args hold the command-line arguments from which flags will be parsed.
	// By default is nil and then os.Args will be used.
	// Unless loader.Flags() will be explicitly parsed by the user.
	Args []string

	// FileDecoders to enable other than JSON file formats and prevent additional dependencies.
	// Add required submodules to the go.mod and register them in this field.
	// Example:
	//	FileDecoders: map[string]aconfig.FileDecoder{
	//		".yaml": aconfigyaml.New(),
	//		".toml": aconfigtoml.New(),
	//		".env": aconfigdotenv.New(),
	// 	}
	FileDecoders map[string]FileDecoder
	// contains filtered or unexported fields
}

Config to configure configuration loader.

type ConfigFormat

type ConfigFormat string
const (
	JsonFormat ConfigFormat = "json"
	YamlFormat ConfigFormat = "yaml"
	TomlFormat ConfigFormat = "toml"
	HclFormat  ConfigFormat = "hcl"
	EnvFormat  ConfigFormat = "env"
)

type Field

type Field interface {
	// Name of the field.
	Name() string

	// Tag returns a given tag for a field.
	Tag(tag string) string

	// Parent of the current node.
	Parent() (Field, bool)
}

Field of the user configuration structure. Done as an interface to export less things in lib.

type FileDecoder

type FileDecoder interface {
	DecodeFile(filename string) (map[string]interface{}, error)
}

FileDecoder is used to read config from files. See aconfig submodules.

type FileDecoderWithFormat

type FileDecoderWithFormat interface {
	FileDecoder
	FileFormat() ConfigFormat
}

type Loader

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

Loader of user configuration.

func LoaderFor

func LoaderFor(dst interface{}, cfg Config) *Loader

LoaderFor creates a new Loader based on a given configuration structure. Supports only non-nil structures.

func (*Loader) Flags

func (l *Loader) Flags() *flag.FlagSet

Flags returngs flag.FlagSet to create your own flags. FlagSet name is Config.FlagPrefix and error handling is set to ContinueOnError.

func (*Loader) Load

func (l *Loader) Load() error

Load configuration into a given param.

func (*Loader) WalkFields

func (l *Loader) WalkFields(fn func(f Field) bool)

WalkFields iterates over configuration fields. Easy way to create documentation or user-friendly help.

Directories

Path Synopsis
aconfighcl module
aconfigtoml module

Jump to

Keyboard shortcuts

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