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

Overview

Config

PkgGoDev Mentioned in Awesome Go Build Status Go Report Card Coverage Status GitHub issues license Release

Manage your application config as a typesafe struct in as little as two function calls.

type MyConfig struct {
	DatabaseUrl string `config:"DATABASE_URL"`
	FeatureFlag bool   `config:"FEATURE_FLAG"`
	Port        int // tags are optional. PORT is assumed
	...
}

var c MyConfig
err := config.FromEnv().To(&c)

How It Works

It's just simple, pure stdlib.

  • A field's type determines what strconv function is called.

  • All string conversion rules are as defined in the strconv package

  • time.Duration follows the same parsing rules as time.ParseDuration

  • If chaining multiple data sources, data sets are merged. Later values override previous values.

    config.From("dev.config").FromEnv().To(&c)
  • Unset values remain intact or as their native zero value

  • Nested structs/subconfigs are delimited with double underscore

    • e.g. PARENT__CHILD
  • Env vars map to struct fields case insensitively

    • NOTE: Also true when using struct tags.
  • Any errors encountered are aggregated into a single error value

    • the entirety of the struct is always attempted
    • failed conversions (i.e. converting "x" to an int) and file i/o are the only sources of errors
      • missing values are not errors

Why you should use this

  • It's the cloud-native way to manage config. See 12 Factor Apps
  • Simple:
    • only 2 lines to configure.
  • Composeable:
    • Merge local files and environment variables for effortless local development.
  • small:
    • only stdlib
    • < 180 LoC

Design Philosophy

Opinionated and narrow in scope. This library is only meant to do config binding. Feel free to use it on its own, or alongside other libraries.

  • Only structs at the entry point. This keeps the API surface small.

  • Slices are space delimited. This matches how environment variables and commandline args are handled by the go cmd.

  • No slices of structs. The extra complexity isn't warranted for such a niche usecase.

  • No maps. The only feature of maps not handled by structs for this usecase is dynamic keys.

  • No pointer members. If you really need one, just take the address of parts of your struct.

You might also like...
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

Go configuration made easy!

gofigure Go configuration made easy! Just define a struct and call Gofigure Supports strings, ints/uints/floats, slices and nested structs Supports en

Harvest configuration, watch and notify subscriber

Harvester Harvester is a configuration library which helps setting up and monitoring configuration values in order to dynamically reconfigure your app

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

🛠 A configuration library for Go that parses environment variables, JSON files, and reloads automatically on SIGHUP
🛠 A configuration library for Go that parses environment variables, JSON files, and reloads automatically on SIGHUP

config A small configuration library for Go that parses environment variables, JSON files, and reloads automatically on SIGHUP. Example func main() {

Golang library for managing configuration data from environment variables

envconfig import "github.com/kelseyhightower/envconfig" Documentation See godoc Usage Set some environment variables: export MYAPP_DEBUG=false export

Light weight, extensible configuration management library for Go. Built in support for JSON, TOML, YAML, env, command line, file, S3 etc. Alternative to viper.
Light weight, extensible configuration management library for Go. Built in support for JSON, TOML, YAML, env, command line, file, S3 etc. Alternative to viper.

koanf (pronounced conf; a play on the Japanese Koan) is a library for reading configuration from different sources in different formats in Go applicat

A golang package for parsing ini-style configuration files

Mini Mini is a simple ini configuration file parser. The ini syntax supported includes: The standard name=value Comments on new lines starting with #

A dead simple configuration manager for Go applications

Store Store is a dead simple configuration manager for Go applications. I didn't like existing configuration management solutions like globalconf, tac

Comments
  • Allow a global prefix for config field names

    Allow a global prefix for config field names

    Hi Jeremy, I like your config package a lot, minimalist and still covers 99% of the config use cases.

    One thing I am missing is using a global prefix for field names. I deploy to k8s and in our environment, a large number of env vars are automatically injected into containers. It is very helpful therefore, to prefix env vars for instance with the app name. Also, with a prefix there is no risk using a prexisting (injected) name. Example:

    MYAPP__DATABASE_PORT=5432
    

    Would be used like

    var c MyConfig
    err := WithPrefix("MYAPP").From("config").FromEnv().To(&c)
    

    Added "WithPrefix" funcs and a test for that.

    Best regards, Chris

    opened by cbndr 6
  • Add errors, subtract panics

    Add errors, subtract panics

    Add a few extra lines of code, refactor some code, now there's an Error pattern similar to example of bufio.Scanner

    Also added some error handling for type conversion and for scanner.Err()

    opened by freman 3
  • error handling prototype

    error handling prototype

    @freman my stab at error handling. I need to clean a lot up, but I wanted to get your input on it.

    A couple of key points:

    • config is a very high-level API. As such, many different types of errors can happen. In addition, multiple errors can happen at once, and the consumer may want to still continue. Hence, the aggregation.
    • a single error type is returned. This allows easy future API updates while maintaining backwards compatibility, preventing the need for a v2.
    • Adding methods to inspect the type of error is stolen from the net package
    • I think we also need a way to inspect the type of field errors.
      • e.g. a field error on DATABASE_URL is not allowed, but FEATURE_FLAG is allowed.

    I'm debating on removing the type switch, and changing the error API to be similar to the os package

    opened by JeremyLoy 0
  • Add command line args processing

    Add command line args processing

    A concern I have is handling command line args. I personally have the pref to this order of precedence for configuration:

    • config file
    • can be overridden by env vars
    • can be overwritten by command line args

    Would it make sense to add a bit of code for this, or how would you propose to handle this use case?

    I would propose to use separate tags, as normally not all config items should be configurable via command line and the arg names should be different.

    opened by cbndr 1
Releases(v1.5.0)
Owner
Jeremy Loy
☕️ +💻=📱
Jeremy Loy
Lightweight Go library to use in 12-factor apps.

environ Lightweight Go library to use in 12-factor apps. s, err := environ.E("FOO").AsString() s, err := environ.E("FOO").Default("foo_value").AsStrin

Petr K. 0 Jan 5, 2022
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

Heetch 455 Nov 26, 2022
Little Go tool to infer an uncrustify config file from an expected format

uncrustify-infer Little Go tool to infer an uncrustify config file from an expected format Install This tool relies on an uncrustify executable, you m

xdrm-brackets 0 Oct 8, 2021
A Go library for parsing struct tags from environment variables.

Envconfig Envconfig populates struct field values based on environment variables or arbitrary lookup functions. It supports pre-setting mutations, whi

Seth Vargo 697 Dec 1, 2022
✨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

Ilya Kaznacheev 817 Dec 7, 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

Oleg Lebedev 259 Nov 17, 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

Harrison Shoebridge 57 Sep 26, 2022
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

Sherif Abdel-Naby 82 Oct 30, 2022
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

Vincent Rischmann 229 Nov 3, 2022
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

null 243 Nov 11, 2022