config

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: May 26, 2023 License: MIT Imports: 17 Imported by: 0

README

build coverage goreport

Light-weight configuration parsing

Package config can be used to parse flags, environmental variables and configuration files, and store them in a given struct.

The priority of the sources is the following:

  1. flags
  2. env. variables
  3. given config file
  4. flag defaults
  5. default config file

For example, if values from the following sources were loaded:

Defaults : {
		"user": "default",
		"secret": "",
		"endpoint": "https:localhost"
        "port": 99,
}

Given config file : {
		"user": "root"
		"secret": "confsecret"
}

Env : {
		"secret": "somesecretkey"
        "port": 88
}

Flags : {
        "port": 77 
}

The resulting config will have the following values:

	{
		"user": "root",
		"secret": "somesecretkey",
		"endpoint": "https:localhost"
        "port": 77,
	}

Supported file types

The config files may be of the following types:

  • toml
  • yml
  • json

Keep in mind

  • There is no case sensitivty, i.e. "pim", "Pim" and "PIM" are all considered the same
  • The names of the environmental variables must match that of the struct. It is possible to set a prefix, so that i.e. if "MYVAR_" is set as a prefix, "MYVAR_PIM" will map to the property "pim"/"Pim"/"PIM".
  • For flags to map to the config automatically they must have the same name

Currently not supported

  • Anonymous structs for yaml files. Example:
type Inner struct {
	hello string
}

type Outer struct {
	Inner
	goodbye string
}

This is due to how the standard yml packages (currently) parses structs.

  • Setting more complex structures via flags.

Example, in the case of this struct

type MyConfig struct {
	Debug   bool   `yaml:"debug" toml:"debug"`
	Log     string `yaml:"log" toml:"log"`

	Local struct {
		Host string `yaml:"host" toml:"host"`
		Port int    `yaml:"port" toml:"port"`
	} `yaml:"local" toml:"local"`

	Remote struct {
		Host string `yaml:"host" toml:"host"`
		Port int    `yaml:"port" toml:"port"`
	} `yaml:"remote" toml:"remote"`
}

for the flags -host / -port, the first corresponding property will be set, which in this case is the Local struct's properties.

Documentation

Index

Constants

View Source
const (
	ContinueOnError = ErrorHandling(flag.ContinueOnError) // Return a descriptive error.
	ExitOnError     = ErrorHandling(flag.ExitOnError)     // Call os.Exit(2) or for -h/-help Exit(0).
	PanicOnError    = ErrorHandling(flag.PanicOnError)    // Call panic with a descriptive error.
)

Variables

View Source
var (
	ErrNoDefaultConfig            = errors.New("no default config file to parse")
	ErrFailedToParseDefaultConfig = fmt.Errorf("failed to parse default config (%s)", defaultFile)
	ErrNotAPointer                = errors.New("argument to must be a pointer")
	ErrInvalidConfigFile          = errors.New("unsupported or invalid file")
	ErrInvalidFormat              = errors.New("invalid format of file")
	ErrNoConfigFileToParse        = errors.New("no file given to parse")
	ErrNoFileFound                = syscall.Errno(2) // "could not find file"
)

Functions

func GetDefaultFile

func GetDefaultFile() string

func GetDefaultFlags

func GetDefaultFlags() map[string]interface{}

Returns a map of all flag defaults. The key is the flag name and the value the flag's default value.

func Init added in v0.0.5

func Init(errorHandling ErrorHandling)

Init sets the global error handling property, as well as the error handling property for the flagset.

The error handling for the config package is similar to that of the standard flag package; there are three modes: Continue, Panic and Exit.

The default mode is Continue.

func LookupFlag

func LookupFlag(name string) *flag.Flag

Returns the Flag structure of the named flag of the global flag set, returning nil if none exists. By default, the global flag set is that of the command-line.

func ParseConfigFile

func ParseConfigFile(cfg interface{}, filename string, dirs ...string) (err error)

Parse the given config fiĺe into the value pointed to by cfg. Returns error regardless of error handling scheme.

If cfg is not a pointer, ParseConfigFile returns an ErrNotAPointer.

The 'filename' must either be an absolute path to the config file, exist in the current working directory, or in one of the directories given as 'dirs'. If the given file cannot be found, ParseConfig file returns an ErrNoConfigFileToParse.

func ParseDefaultConfigFile

func ParseDefaultConfigFile(cfg interface{}) (err error)

Parse the default config fiĺe into the value pointed to by cfg. Returns error regardless of error handling mode.

If cfg is not a pointer, ParseDefaultConfigFile returns an ErrNotAPointer.

func ParseFlags

func ParseFlags() error

Parses flags, stores all default flags in a list, and all parsed flags in another.

func ParsedFlag

func ParsedFlag(f *flag.Flag) bool

Checks if a flag has been parsed.

func SetDefaultFile

func SetDefaultFile(fpath string) (err error)

Set default file. fpath must be absolute path. If the file cannot be opened, the function will return an error. Note that the error will only be return if the error handling mode is set to ContinueOnError, else the function will Panic or Exit depending on the mode.

func SetEnvPrefix

func SetEnvPrefix(prefix string)

Set a prefix to use for all environmental variables.

For example to different between what is used in testing and otherwise, the prefix "TEST_" could be used. The environmental variables TEST_timeout and TEST_angle would then map to the properties 'timeout' and 'angle'.

func SetEnvsToParse

func SetEnvsToParse(envVarNames []string) (err error)

Set a list of environmental variable names to check when filling out the configuration struct.

The list can consist of variables both containing a set env prefix and not, but the environmental variable that is looked for will be that with the prefix. That is, if the prefix is set as TEST_ and the list envVarNames is ["timeout", "TEST_angle"], the environmental variables that will be looked for are ["TEST_timeout", "TEST_angle"].

If the environmental variable(s) cannot be find, SetEnvsToParse will return an error containing all the names of the non-existant variables. Note that the error will only be return if the error handling mode is set to ContinueOnError, else the function will Panic or Exit depending on the mode.

func SetFlagDefault

func SetFlagDefault(fName, def string) error

Set, or reset, the default value of a flag.

func SetFlagSet

func SetFlagSet(f *flag.FlagSet)

Set config package's global FlagSet.

func SetFlagSetArgs

func SetFlagSetArgs(args []string)

Set a list of flags to parse. As default, args is set os os.Args[1:], the command-line args.

SetFlagSetArgs is particularly useful for testing.

func SetUpConfiguration

func SetUpConfiguration(cfg interface{}) (err error)

Parse all the sources (flags, env vars, default config file) and store the result in the value pointer to by cfg.

If cfg is not a pointer, SetUpConfiguration returns an ErrNotAPointer.

func SetUpConfigurationWithConfigFile

func SetUpConfigurationWithConfigFile(cfg interface{}, filename string, dirs ...string) (err error)

Parse all the sources (flags, env vars, given config file, default config file) and store the result in the value pointer to by cfg.

If cfg is not a pointer, SetUpConfigurationWithConfigFile returns an ErrNotAPointer.

The 'filename' must either be an absolute path to the config file, exist in the current working directory, or in one of the directories given as 'dirs'. If the given file cannot be found, the other sources will still be parsed, but an ErrNoConfigFileToParse will be returned.

func String added in v0.0.5

func String(c interface{}) string

Creates a string given a ptr to a struct.

Example:

 type Person struct {
	Name string
 	Age int
 }

 func printMio() {
	 mio := &Person{Name: "Mio", Age: 9}
	 fmt.Println(String(mio))
 }

output:

name: Mio
age: 9

func StringIgnoreZeroValues added in v0.0.5

func StringIgnoreZeroValues(c interface{}) string

Same as String(), except ignores zero values e.g. empty strings and zeroes

func Usage added in v0.0.5

func Usage()

Usage prints a usage message documenting all defined command-line flags to the set FlagSet's output, which by default is os.Stderr. It is based on the standard flag package's PrintDefaults() but includes two more default flags in addition to 'help': write-def-conf (write to default config file) and print-conf (print current configuration to stdout).

Usage is called when an error occurs while parsing flags.

Types

type ErrorHandling added in v0.1.0

type ErrorHandling flag.ErrorHandling

Aliasing flag.Errorhandling for clarity and easy of use.

type FlagValue

type FlagValue struct {
	Value flag.Value
	// contains filtered or unexported fields
}

FlagValue is a wrapper for flag.Value, which stores the dynamic value of a flag, and information on if the flag has been parsed.

func (*FlagValue) Set

func (fv *FlagValue) Set(val string) error

Intercepts the standard flag package's Set().

func (*FlagValue) String

func (fv *FlagValue) String() string

Intercepts the standard flag package's String().

type FlagValueBool added in v0.0.4

type FlagValueBool struct {
	FlagValue
}

Implements flag package's boolFlag interface. Special case to enable using bool flags like switches.

func (*FlagValueBool) IsBoolFlag added in v0.0.4

func (fvb *FlagValueBool) IsBoolFlag() bool

Intercepts the standard flag package's IsBoolFlag().

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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