envconf

package module
v1.2.1 Latest Latest
Warning

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

Go to latest
Published: Sep 14, 2023 License: MIT Imports: 14 Imported by: 5

README

EnvConf

Go Report GoDoc Build and Test codecov

EnvConf is a Go package, for parsing configuration values from different sources.

Installing

go get github.com/antonmashko/envconf

Parse Configs

Usually you need a tag with desire configuration sources and execution of a single function envconf.Parse for getting all configuration values into your golang structure.

Supported Configurations
  • command line flags
  • environment variables
  • default values
  • external sources (can be anything that is implementing interface External)
Tags

Use tags for getting values from different configuration sources.

  • flag - name of flag;
  • env - name of environment variable;
  • default - if nothing set this value will be used as field value;
  • required - on true checks that configuration exists in flag or env source;
  • description - field description in help output.
  • envconf - only for structs. override struct name for generating configuration name.
Supported Types
  1. Primitives: bool, string, all types of int and unit, float32, float64, complex64, complex128;
  2. Collections:
    • Array and Slice - comma-separated string can be converted into slice or array. NOTE: if elements in string more than len of array EnvConf will panic with index out of range.
    • Map - comma-separated string with a colon-separated key and value can be converted into map. example input: key1:value1, key2:value2
  3. Golang types:
    • time.Duration;
    • time.Time - using time.RFC3339 as a time.Parse layout argument;
    • net.IP;
    • url.URL;
Example

Let's take a look at a simple example. Here we're creating struct with 3 tags for different configuration sources: flag, env, and default value. NOTE: It's not necessary to specify tags for each configuration type, add desired only

package main

import (
	"fmt"

	"github.com/antonmashko/envconf"
)

type Example struct {
	Field1 string `flag:"flag-name" env:"ENV_VAR_NAME" default:"default-value"`
}

func main() {
	var cfg Example
	if err := envconf.Parse(&cfg); err != nil {
		panic(err)
	}
	fmt.Printf("%#v\n", cfg)
}

Testing! If you want to get set Field1 from command line flag, use flag name that is set in flag tag.

$ go run main.go -flag-name="variable-from-flag"
main.Example{Field1:"variable-from-flag"}

The same result would be for other configuration types.

-help output

Using envconf will also generate help output with all registered fields and types. Use flag -help or -h for getting it.

$ go run main.go -help

Usage:

Field1 <string> default-value
        flag: flag-name
        environment variable: ENV_VAR_NAME
        required: false
        description: ""

Auto-generating Config Names

EnvConf can generate environment variable name or flag name from golang field path. All you need is to set * in specific tag. For environment variables name envconf will use field path in uppercase and underscore as a delimiter. Example:

type Config struct {
	HTTP struct {
		Addr string `env:"*"`
	}
}

Now we can use HTTP_ADDR environment variable for defining Addr field. The same approach will work for flag. But flag names will be generated in lowercase and the dash will be as a delimiter.

Overriding Parent struct name for Auto-generation

In case if parent struct name doesn't satisfy for configuration variable name, it can be changed with envconf tag. Example:

type Config struct {
	HTTP struct {
		Addr string `env:"*"`
	} `envconf:"httpserver"`
}

Now we'll get HTTPSERVER_ADDR as environment variable name. See: EnvConf example

Configuration Priority

Priority:

1) Flag 
2) Environment variable 
3) External source
4) Default value

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrNilData = errors.New("nil data")

ErrNilData mean that exists nil pointer inside data struct

View Source
var (
	ErrUnsupportedType = errors.New("unsupported type")
)
View Source
var FlagParsed func() error

FlagParsed define this callback when you need handle flags This callback will raise after method flag.Parse() return not nil error interrupt pasring

View Source
var UseCustomHelp = true

UseCustomHelp override default flag `Usage`

Functions

func Parse

func Parse(data interface{}) error

Parse define variables inside data from different sources, such as flag/environment variable or default value

func ParseWithExternal

func ParseWithExternal(data interface{}, external External) error

ParseWithExternal works same as Parse method but also can be used external sources (config files, key-value storages, etc.).

func SetLogger

func SetLogger(logger Logger)

SetLogger define debug logger. This logger will print defined values in data fields

func SetPriority

func SetPriority(s ...ConfigSource)

SetPriority overrides default priority order. Default priority order is: Flag, Environment variable, External source, Default value.

Types

type ConfigSource added in v1.1.0

type ConfigSource int
const (
	FlagVariable ConfigSource = iota
	EnvVariable
	ExternalSource
	DefaultValue
)

func (ConfigSource) String added in v1.1.0

func (s ConfigSource) String() string

type EnvConf added in v1.1.0

type EnvConf struct {
	Logger Logger
	// contains filtered or unexported fields
}

func New added in v1.1.0

func New() *EnvConf

func NewWithExternal added in v1.1.0

func NewWithExternal(e External) *EnvConf

func (*EnvConf) Parse added in v1.1.0

func (e *EnvConf) Parse(data interface{}) error

Parse define variables inside data from different sources, such as flag/environment variable or default value

func (*EnvConf) PriorityOrder added in v1.1.0

func (e *EnvConf) PriorityOrder() []ConfigSource

PriorityOrder return parsing priority order

func (*EnvConf) SetPriorityOrder added in v1.1.0

func (e *EnvConf) SetPriorityOrder(s ...ConfigSource)

SetPriorityOrder overrides default priority order. Default priority order is: Flag, Environment variable, External source, Default value.

type Error

type Error struct {
	Inner     error
	Message   string
	FieldName string
}

func (*Error) Error

func (e *Error) Error() string

type External

type External interface {
	TagName() string
	Unmarshal(interface{}) error
}

External config source

type JsonConfig

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

func NewJsonConfig

func NewJsonConfig() *JsonConfig

func (*JsonConfig) Read

func (j *JsonConfig) Read(data []byte)

func (*JsonConfig) TagName added in v1.2.0

func (j *JsonConfig) TagName() string

func (*JsonConfig) Unmarshal

func (j *JsonConfig) Unmarshal(v interface{}) error

type Logger

type Logger interface {
	Printf(string, ...interface{})
	Println(...interface{})
}

type Var added in v1.1.0

type Var interface {
	Name() string
	Value() (string, bool)
}

Var is configuration variable for defining primitive data types

Directories

Path Synopsis
external
yaml module

Jump to

Keyboard shortcuts

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