aconfig

package module
v0.18.5 Latest Latest
Warning

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

Go to latest
Published: Sep 3, 2023 License: MIT Imports: 12 Imported by: 60

README

aconfig

build-img pkg-img version-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 is as easy to use and understand as possible. 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 these 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/cristalhq/aconfig

Example

type MyConfig struct {
	Port int `default:"1111" usage:"just give a number"`
	Auth struct {
		User string `required:"true"`
		Pass string `required:"true"`
	}
	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.

Example (Defaults)

Just load defaults from struct definition.

package main

import (
	"fmt"
	"log"

	"github.com/cristalhq/aconfig"
)

type MyConfig struct {
	HTTPPort int `default:"1111" usage:"just a number"`
	Auth     struct {
		User string `default:"def-user" usage:"your user"`
		Pass string `default:"def-pass" usage:"make it strong"`
	}
}

func main() {
	var cfg MyConfig
	loader := aconfig.LoaderFor(&cfg, aconfig.Config{
		SkipFiles: true,
		SkipEnv:   true,
		SkipFlags: true,
	})
	if err := loader.Load(); err != nil {
		log.Panic(err)
	}

	fmt.Printf("HTTPPort:  %v\n", cfg.HTTPPort)
	fmt.Printf("Auth.User: %v\n", cfg.Auth.User)
	fmt.Printf("Auth.Pass: %v\n", cfg.Auth.Pass)

}
Output:


HTTPPort:  1111
Auth.User: def-user
Auth.Pass: def-pass
Example (Env)

Load defaults from struct definition and overwrite with a file. And then overwrite with environment variables.

package main

import (
	"fmt"
	"log"
	"os"

	"github.com/cristalhq/aconfig"
)

type MyConfig struct {
	HTTPPort int `default:"1111" usage:"just a number"`
	Auth     struct {
		User string `default:"def-user" usage:"your user"`
		Pass string `default:"def-pass" usage:"make it strong"`
	}
}

func main() {
	os.Setenv("EXAMPLE_HTTP_PORT", "3333")
	os.Setenv("EXAMPLE_AUTH_USER", "env-user")
	os.Setenv("EXAMPLE_AUTH_PASS", "env-pass")
	defer os.Clearenv()

	var cfg MyConfig
	loader := aconfig.LoaderFor(&cfg, aconfig.Config{
		SkipFlags: true,
		EnvPrefix: "EXAMPLE",
		Files:     []string{"testdata/example_config.json"},
	})
	if err := loader.Load(); err != nil {
		log.Panic(err)
	}

	fmt.Printf("HTTPPort:  %v\n", cfg.HTTPPort)
	fmt.Printf("Auth.User: %v\n", cfg.Auth.User)
	fmt.Printf("Auth.Pass: %v\n", cfg.Auth.Pass)

}
Output:


HTTPPort:  3333
Auth.User: env-user
Auth.Pass: env-pass
Example (File)

Load defaults from struct defunition and overwrite with a file.

package main

import (
	"fmt"
	"log"

	"github.com/cristalhq/aconfig"
)

type MyConfig struct {
	HTTPPort int `default:"1111" usage:"just a number"`
	Auth     struct {
		User string `default:"def-user" usage:"your user"`
		Pass string `default:"def-pass" usage:"make it strong"`
	}
}

func main() {
	var cfg MyConfig
	loader := aconfig.LoaderFor(&cfg, aconfig.Config{
		SkipEnv:   true,
		SkipFlags: true,
		Files:     []string{"testdata/example_config.json"},
	})
	if err := loader.Load(); err != nil {
		log.Panic(err)
	}

	fmt.Printf("HTTPPort:  %v\n", cfg.HTTPPort)
	fmt.Printf("Auth.User: %v\n", cfg.Auth.User)
	fmt.Printf("Auth.Pass: %v\n", cfg.Auth.Pass)

}
Output:


HTTPPort:  2222
Auth.User: json-user
Auth.Pass: json-pass
Example (Flag)

Load defaults from struct definition and overwrite with a file. And then overwrite with environment variables. Finally read command line flags.

package main

import (
	"fmt"
	"log"
	"os"

	"github.com/cristalhq/aconfig"
)

type MyConfig struct {
	HTTPPort int `default:"1111" usage:"just a number"`
	Auth     struct {
		User string `default:"def-user" usage:"your user"`
		Pass string `default:"def-pass" usage:"make it strong"`
	}
}

func main() {
	var cfg MyConfig
	loader := aconfig.LoaderFor(&cfg, aconfig.Config{
		FlagPrefix: "ex",
		Files:      []string{"testdata/example_config.json"},
	})

	flags := loader.Flags() // <- IMPORTANT: use this to define your non-config flags
	flags.String("my.other.port", "1234", "debug port")

	// IMPORTANT: next statement is made only to hack flag params
	// to make test example work
	// feel free to remove it completely during copy-paste :)
	os.Args = append([]string{}, os.Args[0],
		"-ex.http_port=4444",
		"-ex.auth.user=flag-user",
		"-ex.auth.pass=flag-pass",
	)
	if err := flags.Parse(os.Args[1:]); err != nil {
		log.Panic(err)
	}

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

	fmt.Printf("HTTPPort:  %v\n", cfg.HTTPPort)
	fmt.Printf("Auth.User: %v\n", cfg.Auth.User)
	fmt.Printf("Auth.Pass: %v\n", cfg.Auth.Pass)

}
Output:


HTTPPort:  4444
Auth.User: flag-user
Auth.Pass: flag-pass
Example (SimpleUsage)
package main

import (
	"fmt"
	"log"

	"github.com/cristalhq/aconfig"
)

type MyConfig struct {
	HTTPPort int `default:"1111" usage:"just a number"`
	Auth     struct {
		User string `default:"def-user" usage:"your user"`
		Pass string `default:"def-pass" usage:"make it strong"`
	}
}

func main() {
	var cfg MyConfig
	loader := aconfig.LoaderFor(&cfg, aconfig.Config{
		SkipDefaults: true,
		SkipFiles:    true,
		SkipEnv:      true,
		SkipFlags:    true,
		Files:        []string{"/var/opt/myapp/config.json"},
		EnvPrefix:    "APP",
		FlagPrefix:   "app",
	})
	if err := loader.Load(); err != nil {
		log.Panic(err)
	}

	fmt.Printf("HTTPPort:  %v\n", cfg.HTTPPort)
	fmt.Printf("Auth.User: %q\n", cfg.Auth.User)
	fmt.Printf("Auth.Pass: %q\n", cfg.Auth.Pass)

}
Output:


HTTPPort:  0
Auth.User: ""
Auth.Pass: ""
Example (WalkFields)
package main

import (
	"fmt"

	"github.com/cristalhq/aconfig"
)

type MyConfig struct {
	HTTPPort int `default:"1111" usage:"just a number"`
	Auth     struct {
		User string `default:"def-user" usage:"your user"`
		Pass string `default:"def-pass" usage:"make it strong"`
	}
}

func main() {
	var cfg MyConfig
	loader := aconfig.LoaderFor(&cfg, aconfig.Config{
		SkipFiles: true,
		SkipEnv:   true,
		SkipFlags: true,
	})
	loader.WalkFields(func(f aconfig.Field) bool {
		fmt.Printf("%v: %q %q %q %q\n", f.Name(), f.Tag("env"), f.Tag("flag"), f.Tag("default"), f.Tag("usage"))
		return true
	})

}
Output:

HTTPPort: "HTTP_PORT" "http_port" "1111" "just a number"
Auth.User: "USER" "user" "def-user" "your user"
Auth.Pass: "PASS" "pass" "def-pass" "make it strong"

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Config added in v0.9.0

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

	// AllowDuplicates set to true will not fail on duplicated names on fields (env, flag, etc...)
	AllowDuplicates 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

	// FileSystem from which files will be loaded. Default is nil (OS file system).
	FileSystem fs.FS

	// 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 the name of the flag that defines the path to the configuration file passed through the CLI.
	// (To make it easier to transfer the config file via flags.)
	FileFlag string

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

	// Envs hold the environment variable from which envs will be parsed.
	// By default is nil and then os.Environ() will be used.
	Envs []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 Field added in v0.4.0

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 added in v0.8.0

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

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

type Loader

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

Loader of user configuration.

func LoaderFor added in v0.2.1

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 added in v0.1.2

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 added in v0.4.0

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
aconfigyaml module

Jump to

Keyboard shortcuts

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