gonfig

package module
v0.7.1 Latest Latest
Warning

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

Go to latest
Published: May 5, 2023 License: MIT Imports: 7 Imported by: 0

README

PkgGoDev Test workflow Go Report Codecov
Become a sponsor Donate Paypal

About

This library is heavily inspired by the traefik config package. It offers a simple and performant config handling with:

  • Configuration files in YAML or TOML format
  • Environment variables
  • Flag arguments

An example is available here.

Installation

go get github.com/crazy-max/gonfig

Contributing

Want to contribute? Awesome! The most basic way to show your support is to star the project, or to raise issues. You can also support this project by becoming a sponsor on GitHub or by making a Paypal donation to ensure this journey continues indefinitely!

Thanks again for your support, it is much appreciated! 🙏

License

MIT. See LICENSE for more details.

Documentation

Overview

Lightweight config handling for Go.

This library is heavily inspired by the traefik config package. It offers a simple and performant config handling with: - Configuration files in YAML or TOML format - Environment variables - Flag arguments

Get started:

func init() {
	// Typically done outside of the app
	_ = os.Setenv("MYAPP_SERVER_FTP_HOST", "test.rebex.net")
	_ = os.Setenv("MYAPP_SERVER_FTP_USERNAME", "demo")
	_ = os.Setenv("MYAPP_SERVER_FTP_PASSWORD", "password")
	_ = os.Setenv("MYAPP_SERVER_FTP_SOURCES", "/src1,/src2")
}

func main() {
	cfg := Config{
		Db: (&Db{}).GetDefaults(),
	}

	// Load from file(s)
	fileLoader := gonfig.NewFileLoader(gonfig.FileLoaderConfig{
		Filename: "/path/to/myapp.yml",
		Finder: gonfig.Finder{
			BasePaths:  []string{"/etc/myapp/myapp", "$XDG_CONFIG_HOME/myapp", "$HOME/.config/myapp", "./myapp"},
			Extensions: []string{"yaml", "yml"},
		},
	})
	if found, err := fileLoader.Load(&cfg); err != nil {
		log.Fatal(errors.Wrap(err, "Failed to decode configuration from file"))
	} else if !found {
		log.Println("No configuration file found")
	} else {
		log.Printf("Configuration loaded from file: %s", fileLoader.GetFilename())
	}

	// Load from flags
	flagsLoader := gonfig.NewFlagLoader(gonfig.FlagLoaderConfig{
		Args: []string{
			"--timezone=Europe/Paris",
			"--logLevel=debug",
		},
	})
	if found, err := flagsLoader.Load(&cfg); err != nil {
		log.Fatal(errors.Wrap(err, "Failed to decode configuration from flags"))
	} else if !found {
		log.Println("No flags found")
	} else {
		log.Printf("Configuration loaded from flags")
	}

	// Load from environment variables
	envLoader := gonfig.NewEnvLoader(gonfig.EnvLoaderConfig{
		Prefix: "MYAPP_",
	})
	if found, err := envLoader.Load(&cfg); err != nil {
		log.Fatal(errors.Wrap(err, "Failed to decode configuration from environment variables"))
	} else if !found {
		log.Println("No MYAPP_* environment variables defined")
	} else {
		log.Printf("Configuration loaded from %d environment variables\n", len(envLoader.GetVars()))
	}

	// Display configuration
	b, _ := json.MarshalIndent(cfg, "", "  ")
	fmt.Println(string(b))
}

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type EnvLoader

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

EnvLoader is the structure representring an environment variable loader.

func NewEnvLoader

func NewEnvLoader(cfg EnvLoaderConfig) *EnvLoader

New creates a new Loader from the EnvLoaderConfig cfg.

func (*EnvLoader) GetVars

func (l *EnvLoader) GetVars() []string

GetVars returns the environment variables found.

func (*EnvLoader) Load

func (l *EnvLoader) Load(cfg interface{}) (bool, error)

Load loads the configuration from the environment variables.

type EnvLoaderConfig

type EnvLoaderConfig struct {
	// Prefix to use. Default to "GONFIG_"
	Prefix string
}

EnvLoaderConfig loads a configuration from environment variables.

type FileLoader

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

FileLoader is the structure representring a file loader.

func NewFileLoader

func NewFileLoader(cfg FileLoaderConfig) *FileLoader

New creates a new Loader fromt the FileLoaderConfig cfg.

func (*FileLoader) GetFilename

func (l *FileLoader) GetFilename() string

GetFilename returns the configuration file if any.

func (*FileLoader) Load

func (l *FileLoader) Load(cfg interface{}) (bool, error)

Load loads the configuration from a file and/or finders.

type FileLoaderConfig

type FileLoaderConfig struct {
	Filename string
	Finder   Finder
}

FileLoader loads a configuration from a file.

type Finder

type Finder struct {
	BasePaths  []string
	Extensions []string
}

Finder holds a list of file paths.

func (Finder) Find

func (f Finder) Find(configFile string) (string, error)

Find returns the first valid existing file among configFile and the paths already registered with Finder.

type FlagLoader

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

FlagLoader is the structure representring a flag loader.

func NewFlagLoader

func NewFlagLoader(cfg FlagLoaderConfig) *FlagLoader

New creates a new Loader from the FlagLoaderConfig cfg.

func (*FlagLoader) Load

func (l *FlagLoader) Load(cfg interface{}) (bool, error)

Load loads the configuration from flags.

type FlagLoaderConfig

type FlagLoaderConfig struct {
	// Args are command line arguments.
	Args []string
}

FlagLoaderConfig loads a configuration from flags.

type Loader

type Loader interface {
	// Load populates cfg.
	Load(cfg interface{}) (bool, error)
}

Loader is a configuration resource loader.

Directories

Path Synopsis
Package env implements encoding and decoding between environment variable and a typed Configuration.
Package env implements encoding and decoding between environment variable and a typed Configuration.
Package file implements decoding between configuration in a file and a typed Configuration.
Package file implements decoding between configuration in a file and a typed Configuration.
Package flag implements encoding and decoding between flag arguments and a typed Configuration.
Package flag implements encoding and decoding between flag arguments and a typed Configuration.
Package generator implements the custom initialization of all the fields of an empty interface.
Package generator implements the custom initialization of all the fields of an empty interface.
Package parser implements decoding and encoding between a flat map of labels and a typed Configuration.
Package parser implements decoding and encoding between a flat map of labels and a typed Configuration.

Jump to

Keyboard shortcuts

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