Tag based configuration loader from different providers

Gonfig

Go Reference Build Status codecov Go Report Card GitHub release License: MIT Mentioned in Awesome Go

Tag-based configuration parser which loads values from different providers into typesafe struct.

Installation

This package needs go version 1.15+

go get -u github.com/miladabc/gonfig

Usage

package main

import (
    "fmt"
    "net/url"
    "time"

    "github.com/miladabc/gonfig"
)

// Unexported struct fields are ignored
type Config struct {
	Host     string
	Log      bool
	Expiry   int
	Port     uint
	Pi       float64
	Com      complex128
	Byte     byte
	Rune     rune
	Duration time.Duration
	Time     time.Time
	url      url.URL
	Redis    struct {
		Hosts []string
		Ports []int
	}
}

func main() {
	var c Config

	// Input argument must be a pointer to struct
	err := gonfig.Load().FromEnv().Into(&c)
	if err != nil {
		fmt.Println(err)
	}
}

Tags

All the tags are optional.

Config

config tag is used to change default key for fetching the value of field.

type Config struct {
	HostName string `config:"HOST"`
}

func main() {
	var c Config

	os.Setenv("HOST", "golang.org")
	gonfig.Load().FromEnv().Into(&c)
}

File related tags

json, yaml and toml tags are used to change default key for fetching the value from file.

type Config struct {
	HostName string `json:"host" yaml:"host" toml:"host"`
}

func main() {
	var c Config

	gonfig.Load().FromFile("config.json").Into(&c)
}

Default

default tag is used to declare a default value in case of missing value.

type Config struct {
	Host url.URL `default:"golang.org"`
}

Required

required tag is used to make sure a value is present for corresponding field.
Fields are optional by default.

type Config struct {
	Host url.URL `required:"true"`
}

Ignore

ignore tag is used to skip populating a field. Ignore is false by default.

type Config struct {
	Ignored     int `ignore:"true"`
	AlsoIgnored int `config:"-"`
}

Expand

expand tag is used to expand value from OS environment variables.
Expand is false by default.

type Config struct {
	Expanded int `expand:"true" default:"${ENV_VALUE}"`
}

func main() {
	var c Config

	os.Setenv("ENV_VALUE", "123")
	gonfig.Load().FromEnv().Into(&c)
	fmt.Println(c.Expanded) // 123
}

Separator

separator tag is used to separate slice/array items.
Default separator is a single space.

type Config struct {
	List []int `separator:"," default:"1, 2, 3"`
}

Format

format tag is used for parsing time strings.
Default format is time.RFC3339.

type Config struct {
	Time time.Time `format:"2006-01-02T15:04:05.999999999Z07:00"`
}

Providers

Providers can be chained together and they are applied in the specified order.
If multiple values are provided for a field, last one will get applied.

Supported providers

  • Environment variables
  • files
    • .json
    • .yaml (.yml)
    • .toml
    • .env
func main() {
	var c Config

	gonfig.
		Load().
		FromEnv().
		FromFile("config.json").
		FromFile("config.yaml").
		FromFile("config.toml").
		FromFile(".env").
		AddProvider(CustomProvider).
		Into(&c)
}

Env Provider

Env provider will populate struct fields based on the hierarchy of struct.

type Config struct {
	PrettyLog bool
	Redis     struct {
		Host string
		Port int
	}
}

func main() {
	var c Config

	gonfig.
		Load().
		FromEnv().
		Into(&c)
}

It will check for following keys:

  • PRETTY_LOG
  • REDIS_HOST
  • REDIS_PORT

To change default settings, make an EnvProvider and add it to the providers list manually:

type Config struct {
	PrettyLog bool
	Redis     struct {
		Host string
		Port int
	}
}

func main() {
	var c Config

	ep := gonfig.EnvProvider{
		Prefix:         "APP_", // Default to ""
		SnakeCase:      false,  // Defaults to true
		UpperCase:      false,  // Defaults to true
		FieldSeparator: "__",   // Defaults to "_"
		Source:         ".env", // Defaults to OS env vars
		Required:       true,   // Defaults to false
	}

	gonfig.
		Load().
		AddProvider(&ep).
		Into(&c)
}

It will check for following keys in .env file:

  • APP_PrettyLog
  • APP_Redis__Host
  • APP_Redis__Port

File Provider

File provider uses third party parsers for parsing files, read their documentation for more info.

Custom Provider

You can use your own provider by implementing Provider interface and one or both Unmarshaler and Filler interfaces.

type CustomProvider struct{}

func (cp *CustomProvider) Name() string {
	return "custom provider"
}

func (cp *CustomProvider) UnmarshalStruct(i interface{}) error {
	// UnmarshalStruct receives a struct pointer and unmarshalls values into it.
	return nil
}

func (cp *CustomProvider) Fill(in *gonfig.Input) error {
	// Fill receives struct fields and set their values.
	return nil
}

func main() {
	var c Config

	gonfig.
		Load().
		AddProvider(new(CustomProvider)).
		Into(&c)
}

Supported types

Any other type except the followings, results an error

  • string
  • bool
  • int, int8, int16, int32, int64
  • uint, uint8, uint16, uint32, uint64
  • float32, float64
  • complex64, complex128
  • byte
  • rune
  • time.Duration
  • time.Time
  • url.URL
  • pointer, slice and array of above types
  • nested and embedded structs

TODO

Any contribution is appreciated :)

Documentation

Take a look at docs for more information.

License

The library is released under the MIT license.
Checkout LICENSE file.

Owner
Milad Abbasi
Software Engineer
Milad Abbasi
Similar Resources

✨Clean and minimalistic environment configuration reader for Golang

Clean Env Minimalistic configuration reader Overview This is a simple configuration reading tool. It just does the following: reads and parses configu

Jan 8, 2023

12 factor configuration as a typesafe struct in as little as two function calls

Config Manage your application config as a typesafe struct in as little as two function calls. type MyConfig struct { DatabaseUrl string `config:"DAT

Dec 13, 2022

JSON or YAML configuration wrapper with convenient access methods.

Config Package config provides convenient access methods to configuration stored as JSON or YAML. This is a fork of the original version. This version

Dec 16, 2022

Configure is a Go package that gives you easy configuration of your project through redundancy

Configure Configure is a Go package that gives you easy configuration of your project through redundancy. It has an API inspired by negroni and the fl

Sep 26, 2022

An opinionated configuration loading framework for Containerized and Cloud-Native applications.

An opinionated configuration loading framework for Containerized and Cloud-Native applications.

Opinionated configuration loading framework for Containerized and 12-Factor compliant applications. Read configurations from Environment Variables, an

Dec 16, 2022

Load configuration in cascade from multiple backends into a struct

Load configuration in cascade from multiple backends into a struct

Confita is a library that loads configuration from multiple backends and stores it in a struct. Supported backends Environment variables JSON files Ya

Jan 1, 2023

Small library to read your configuration from environment variables

envconfig envconfig is a library which allows you to parse your configuration from environment variables and fill an arbitrary struct. See the example

Nov 3, 2022

A minimalist Go configuration library

A minimalist Go configuration library

fig fig is a tiny library for loading an application's config file and its environment into a Go struct. Individual fields can have default values def

Dec 23, 2022

go-up! A simple configuration library with recursive placeholders resolution and no magic.

go-up! A simple configuration library with placeholders resolution and no magic. go-up provides a simple way to configure an application from multiple

Nov 23, 2022
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
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
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
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 g

Dec 26, 2021
Golang config.yaml loader

Description goconfig is a configuration library designed using the following pri

May 31, 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
Library for setting values to structs' fields from env, flags, files or default tag

Configuration is a library for injecting values recursively into structs - a convenient way of setting up a configuration object. Available features:

Dec 7, 2022
Graph-based Declarative Configuration Language
Graph-based Declarative Configuration Language

Virgo Configuration Language Most configuration problems reduce to graphs, e.g. Dockerfiles and Makefiles But there are no graph-based configuration l

Nov 26, 2022
A port of Namespaces are used to separate different curves

Description Namespaces are used to separate different curves. So for example to support both ED25519 and the NIST P256 curves, one could import into a

Feb 4, 2022