Golang config.yaml loader

Description

goconfig is a configuration library designed using the following principles:

  1. The configuration variables are fully specified and loaded into a struct variable.
  2. You only need one statement to load the configuration fully.
  3. Configuration variables can be retrieved from various sources, in this order of increasing priority:
    • default values from the struct definition
    • the value already in the object when passed into Load()
    • config file in either YAML, TOML, JSON or a custom decoder
    • environment variables
    • command line flags

Furthermore, it has the following features:

  • supported types for interpreting:

    • native Go types: all int, uint, string, bool
    • types that implement TextUnmarshaler from the "encoding" package
    • byte slices ([]byte) are interpreted as base64
    • slices of the above mentioned types
    • map[string]interface{}
  • the location of the config file can be passed through command line flags or environment variables

  • printing help message (and hiding individual flags)

priority

Parse in order of opposite priority: tag, env, file, flags

Documentation

Documentation can be found on godoc.org: https://godoc.org/github.com/asppj/goconfig

// Load loads the configuration of your program in the struct at c.
// Use conf to specify how goconfig should look for configuration variables.
// This method can panic if there was a problem in the configuration struct that
// is used (which should not happen at runtime), but will always try to produce
// an error instead if the user provided incorrect values.
//
// The recognised tags on the exported struct variables are:
//  - id: the keyword identifier (defaults to lowercase of variable name)
//  - default: the default value of the variable
//  - short: the shorthand used for command line flags (like -h)
//  - desc: the description of the config var, used in --help
//  - opts: comma-separated flags.  Supported flags are:
//     - hidden: Hides the option from help outputs.
func Load(c interface{}, conf Conf) error

// Conf is used to specify the intended behavior of goconfig.
type Conf struct {
	// ConfigFileVariable is the config variable that will be read before looking
	// for a config file.  If no value is specified in the environment variables
	// of the command line flags, the default config file will be read.
	// This flag should be defined in the config file struct and referred to here
	// by its ID.  The default value for this variable is obviously ignored.
	ConfigFileVariable string

	// FileDisable disabled reading config variables from the config file.
	FileDisable bool
	// FileDefaultFilename is the default filename to look for for the config
	// file.  If this is empty and no filename is explicitly provided, parsing
	// a config file is skipped.
	FileDefaultFilename string
	// FileDecoder specifies the decoder function to be used for decoding the
	// config file.  The following decoders are provided, but the user can also
	// specify a custom decoder function:
	//  - DecoderYAML
	//  - DecoderTOML
	//  - DecoderJSON
	// If no decoder function is provided, goconfig tries to guess the function
	// based on the file extension and otherwise tries them all in the above
	// mentioned order.
	FileDecoder FileDecoderFn

	// FlagDisable disabled reading config variables from the command line flags.
	FlagDisable bool
	// FlagIgnoreUnknown ignores unknown command line flags instead of stopping
	// with an error message.
	FlagIgnoreUnknown bool

	// EnvDisables disables reading config variables from the environment
	// variables.
	EnvDisable bool
	// EnvPrefix is the prefix to use for the the environment variables.
	// goconfig does not add an underscore after the prefix.
	EnvPrefix string

	// HelpDisable disables printing the help message when the --help or -h flag
	// is provided.  If this is false, an explicit --help flag will be added.
	HelpDisable bool
	// HelpMessage is the message printed before the list of the flags when the
	// user sets the --help flag.
	// The default is "Usage of [executable name]:".
	HelpMessage string
	// HelpDescription is the description to print for the help flag.
	// By default, this is "show this help menu".
	HelpDescription string
}

Usage

type Config struct {
	Color       string `short:"c" default:"red" desc:"color of the thing"`
	Number      int    `short:"n" desc:"number of things"`

    // Use 'id' to change the name of a flag.
	ConfigFile  string `id:"config" short:"C"`
}
var config = Config {
	// alternative way to set default values; they overwrite the ones in the struct
	Number: 42, 
}

// You can also create the config variable inline.
var config = struct {
	Color  string `short:"c" default:"red" desc:"color of the thing"`
}{}

func main() {
	err := goconfig.Load(&config, goconfig.Conf{
		ConfigFileVariable: "config", // enables passing --configfile myfile.conf

		FileDefaultFilename: "myapp.conf",
        // The default decoder will try TOML, YAML and JSON.
		FileDecoder: goconfig.DecoderTOML,

		EnvPrefix: "MYAPP_",
	})
}

Origin

License

goconfig is licensed by an MIT license as can be found in the LICENSE file.

Similar Resources

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

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

🔥🔥 🌈 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

A lightweight config center written by golang.

A lightweight config center written by golang.

Jan 21, 2022

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

A better way to marshal and unmarshal YAML in Golang

YAML marshaling and unmarshaling support for Go Introduction A wrapper around go-yaml designed to enable a better way of handling YAML when marshaling

Jan 4, 2023

Golang Configuration tool that support YAML, JSON, TOML, Shell Environment

Configor Golang Configuration tool that support YAML, JSON, TOML, Shell Environment (Supports Go 1.10+) Usage package main import ( "fmt" "github.c

Dec 29, 2022

Golang library for reading properties from configuration files in JSON and YAML format or from environment variables.

go-config Golang library for reading properties from configuration files in JSON and YAML format or from environment variables. Usage Create config in

Aug 22, 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
Comments
  • Environment variable and file option priority bug

    Environment variable and file option priority bug

    Hi,

    According to README.md the environment variable options are stronger than the ones stored in files. However, it seems that implementation is otherwise, as also the comment suggests: "Parse in order of opposite priority: env, file, flags"

    Is it a bug in the code or the documentation or have I misread something? I would prefer if environment variables would overwrite values set in files, just like the README.md says.

    Thanks.

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 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
Jul 4, 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-yaml - Yaml parsing Toolkit For Golang

go-yaml 介绍 gopkg.in/yaml.v3 已经是个非常好用的包,但是在实际开发中总有类型转换带来的麻烦,go-yaml只是在它的基础上,简单的一层

Jan 13, 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
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
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