A simple multi-layered config loader for Go. Made for smaller projects. No external dependencies.

config

⚠️ Work in progress!

A simple multi-layered config loader for Go.

Made for smaller projects. No external dependencies.

Installation

go get -u github.com/kdevo/config

Example

// Define your configuration struct:
type Config struct {
	RepoOwner   string
	RepoName    string
	URL         string
	HTTPTimeout time.Duration
}

// A config is complete when it can be validated.
// By optionally implementing the Config interface's Validate, we can detect errors.
func (c *Config) Validate() error {
	var errors config.Errors
	if !strings.HasPrefix(c.URL, "http") {
		// Capture errors on a per-field basis by naming the errors accordingly.
		// This way, the config loader knows which fields are valid.
		errors.Add(config.Err("URL", c.URL, "must be a valid URL (starting with http)"))
	}
	if c.HTTPTimeout < 1*time.Second {
		errors.Add(config.Err("HTTPTimeout", c.HTTPTimeout, "must be >= 1s"))
	}
	return errors.AsError() // returns nil if we did not add any error
}

// Config providers follow below signature and return a config and eventually an error.
// There is nothing that prevents the config from being a provider for itself:
func (c *Config) Config() (interface{}, error) {
	return c, c.Validate() // makes some things easier later on
}

// Name the config provider accordingly to make it easily identifiable later on.
func (c *Config) Name() string {
	return "Static"
}

func main() {
	// get config from 'JSON' first, fallback to 'Static' defaults otherwise.
	// we can have any layer of chained config providers by using the builder funcs:
	loader := config.From(provider.JSON("config.json")).
		WithDefaults(&Config{
			RepoOwner: "kdevo",
			RepoName:  "config",
		}) // works because we've implemented the config provider interface above
	var cfg Config
	err := loader.Resolve(&cfg) // calls Validate if implemented
	if err != nil {
		// examine errors by providers to find out the cause:
		fmt.Printf("providers errors: %v\n", loader.ProviderErrors())
	}
	fmt.Printf("got config: %v\n", cfg)
}

Please also take a look at the config loader test.

Loading Rules

  1. Earlier config providers take precedence.
  2. Config structs must be marshable.
  3. Empty/ommitted fields are skipped.
  4. Fields with errors are skipped (see below).

Provider Errors

  1. Returning config.Errors with the specified field names will skip the field.
  2. Field names must follow rules of encoding/json.
  3. Returning regular errors will skip the entire provider (e.g. if the config is corrupt).

Tips:

  1. Skip fields that couldn't be provided by using config.Errors (e.g. when a value has an invalid format).
  2. Use descriptive field names that are unlikely to change.
  3. Return a regular error if we can't provide anything (e.g. Unmarshal error for JSON provider).
Owner
Kai Dinghofer
Passionate Software Engineer
Kai Dinghofer
Similar Resources

Go-based Docker App Loader

go-loader Go-based Docker App Loader Auto-runs uploaded builds with a Docker Container Structures / Home Page /ping Check Docker Container and show st

Feb 11, 2022

Cfginterpolator is an interpolate library in golang allowing to include data from external sources in your configuration

cfginterpolator cfginterpolator is an interpolate library in golang allowing to include data from external sources in your configuration cfginterpolat

Dec 14, 2021

Simple Config Format for Golang.

IndentText Simple Configuration Format that tries to be easy to use and understand at a glance. Unlike other formats, IndentText does not have any typ

Nov 26, 2021

Quick and easy way to load config files based on a simple set of rules.

Quick and easy way to load config files based on a simple set of rules.

config Quick and easy way to load config files based on a simple set of rules. Project inspired by https://github.com/lorenwest/node-config Important

Apr 9, 2021

go implementation of lightbend's HOCON configuration library https://github.com/lightbend/config

HOCON (Human-Optimized Config Object Notation) Configuration library for working with the Lightbend's HOCON format. HOCON is a human-friendly JSON sup

Dec 3, 2022

Composable, observable and performant config handling for Go for the distributed processing era

Konfig Composable, observable and performant config handling for Go. Written for larger distributed systems where you may have plenty of configuration

Dec 11, 2022

🔥🔥 🌈 Golang configuration,use to Viper reading from remote Nacos config systems. Viper remote for Naocs.

Viper remote for Nacos Golang configuration,use to Viper reading from remote Nacos config systems. Viper remote for Naocs. runtime_viper := viper.New(

Dec 6, 2022

create a bootable disk image from Docker image or a yaml config

docker2boot docker2boot creates a bootable disk from either a Docker image or a config yaml file Features status dns Y cloud-init Y network Y ssh TODO

Oct 30, 2022

Nacos is a service config & discovery.

Kratos Nacos example sc := []constant.ServerConfig{ *constant.NewServerConfig("127.0.0.1", 8848), } cc := &constant.ClientConfig{ NamespaceId:

Oct 28, 2021
Related tags
Simple, useful and opinionated config loader.

aconfig Simple, useful and opinionated config loader. Rationale There are many solutions regarding configuration loading in Go. I was looking for a si

Dec 26, 2022
Golang config.yaml loader

Description goconfig is a configuration library designed using the following pri

May 31, 2022
⚙️ Dead Simple Config Management, load and persist config without having to think about where and how.

Configo Dead Simple Config Management, load and persist config without having to think about where and how. Install go get github.com/UltiRequiem/conf

Apr 6, 2022
Go-config - Config parser for go that supports environment vars and multiple yaml files

go-multiconfig This package is able to parse yaml config files. It supports gett

Jun 23, 2022
A lightweight yet powerful config package for Go projects

Config GoLobby Config is a lightweight yet powerful config package for Go projects. It takes advantage of env files and OS variables alongside config

Dec 11, 2022
A local LKM rootkit loader/dropper that lists available security mechanisms
A local LKM rootkit loader/dropper that lists available security mechanisms

A local LKM rootkit loader Introduction This loader can list both user and kernel mode protections that are present on the system, and additionally di

Dec 12, 2022
Go C-based plugins loader

dlplugin This package is based on the official Go plugin package, but modified to use any dynamic C libraries (Only Linux, FreeBSD, and macOS). It pro

Sep 6, 2022
A Go (golang) environment loader (which loads env vars from a .env file)

A Go (golang) environment loader (which loads env vars from a .env file)

Feb 8, 2022
INI Loader written in Go

go-ini INI Loader written in Go Single threaded & simple Examples Read all params func (app MyApp) onParam(name string, value string) bool { app.c

Feb 11, 2022