config

package module
v0.1.4 Latest Latest
Warning

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

Go to latest
Published: Sep 10, 2021 License: Apache-2.0 Imports: 22 Imported by: 6

README

Just another config package

This is here because viper didn't work for me on windows.

Get Started

Example:

type Config struct {
    Host string `yaml:"host" default:"localhost"`
    Port int    `default:"8080"`
    Database struct {
        Name string `default:"postgres"`
        Port int    `default:"5432"`
    } `yaml:"database"`

    Other string `config:"weird-name"`
}

func main() {
    c := &Config{}
    config.SetConfig(c)
    config.SetType("yaml")
    config.AddFile("config.yml") // look for a file named "config.yaml"
    config.AddPath(".")          // look for the config file in "."
    err := config.ReadConfigFile()
    if err == config.NoConfigFile {
        // handle
    }

    // Defaults are set
    fmt.Println(config.GetInt("port")) // 8080
    fmt.Println(config.GetString("database.name")) // postgres
    fmt.Println(config.GetString("database.port")) // 5432

    // Alternate naming
    fmt.Println(config.Get("Other") == config.Get("weird-name")) // true

    // Values are also set on the struct
    fmt.Println(config.GetInt("port") == c.Port) // true
}

Struct tags

For better of for worse, this library relies on struct tags for customization.

tag description
config change config name and give other info
default give the field a default value
env check this environment variable to get a value

Default Values

When initializing a configuration struct, the package will look for the struct tag called default and set the default value from the tag value. This feature only supports a limited number of types such as string types and integer types.

By default, this feature will only work when using the global "getter" functions like config.Get or config.GetInt and will not work for the actual struct that is passed to config.SetConfig. To set the default values to the raw config struct, you need to call config.InitDefaults.

Flag Binding

If you want to change config values using command line options, you can bind the current config struct to a flag set.

Struct tags for flag binding
tag description example
usage usage for the flag config:"name,usage=this is the name flag"
shorthand give the flag a shorthand (only for pflag) config:"name,shorthand=n"
notflag mark the config field as not a flag config:"file,notflag"
// test.go
import "flag"

type Config struct {
    Name string `config:"name,shorthand=n,usage=give the name"`
    Inner struct {
        Val int `config:"val,usage=nested flag"`
    } `config:"inner"`
}
config.SetConfig(&Config{})
config.BindToFlagSet(
    flag.CommandLine,
    config.NewFlagInfo("name", "n", "give the name"),
    config.NewFlagInfo("inner-val", "", "nested flag"),
)
flag.Parse()

Keep in mind that function call order matters here. Calling config.BindToFlagSet before config.SetConfig means that there is no current config struct and will most likely result in a nil pointer panic.

$ go run ./test.go -help
Usage of /tmp/go-build123456789/b001/exe/test:
  -name value
        give the name
  -inner-val value
        nested flag

This feature also supports the common flag package drop in replacement called github.com/spf13/pflag and can be accessed using BindToPFlagSet(set *pflag.FlagSet). The shorthand option is only used with this package.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNoConfigFile is returned when the config file cannot be found.
	ErrNoConfigFile = errors.New("no config file")
	// ErrNoConfigDir is returned when all of the possible config paths
	// do not exist.
	ErrNoConfigDir = errors.New("no config directory")
	// ErrFieldNotFound is returned when the field of a struct
	// was not found with reflection
	ErrFieldNotFound = errors.New("could not find struct field")
	// ErrWrongType is returned when the wrong type is used
	ErrWrongType = errors.New("wrong type")
)
View Source
var IndentedCobraHelpTemplate = `` /* 936-byte string literal not displayed */

This is a template for cobra commands that more closely imitates the style of the go command help message.

Functions

func AddDefaultDirs

func AddDefaultDirs(name string)

AddDefaultDirs sets the config and home directories as possible config dir options.

If the config dir is found (see os.UserConfigDir) then <config dir>/<name> is added to the list of possible config paths. If the home dir is found (see os.UserHomeDir) then <home dir>/<name> is added to the list of possible config paths.

func AddFile added in v0.1.2

func AddFile(name string)

AddFile will add a filename to the list of possible config filenames. This should be the name of a file without any information about the directory or location.

A path and filename could be used and will be treated as relative to any of the paths added with AddPath but is behavior which is not guaranteed to be supported in the future.

To add a directory to the search path, use AddPath.

func AddFilepath added in v0.1.4

func AddFilepath(filepath string)

AddFilepath will add a full filepath to the list of possible config files. This is not the same as adding the path and filename separately. This does not add a search path or filename to search for and should be regarded as hard coding a configuration filepath.

func AddPath

func AddPath(path string)

AddPath will add a path the the list of possible configuration folders where a file could be found. See AddFile to add a file to the list of possible files to be read within a configuration search path.

func AddUserConfigDir added in v0.1.3

func AddUserConfigDir(dirname string) error

AddUserConfigDir will add a config dir using the user config dir (see os.UserConfigDir) and join it with the name given.

$XDG_CONFIG_DIR/<dirname>

func AddUserHomeDir added in v0.1.3

func AddUserHomeDir(name string) error

AddUserHomeDir will add a config dir using the user home dir (see os.UserHomeDir) and join it with the name given and a "."

$HOME/.<name>

func BindToFlagSet added in v0.1.0

func BindToFlagSet(set *flag.FlagSet, resolvers ...FlagInfo)

BindToFlagSet will bind the config struct to a standard library flag set

func BindToPFlagSet added in v0.1.0

func BindToPFlagSet(set *pflag.FlagSet, resolvers ...FlagInfo)

BindToPFlagSet will bind the config object to a pflag set. See https://pkg.go.dev/github.com/spf13/pflag?tab=doc

func DirUsed deprecated

func DirUsed() string

Deprecated: use PathsUsed

func FileUsed deprecated

func FileUsed() string

Deprecated: use FilesUsed

func FilesUsed added in v0.1.4

func FilesUsed() []string

FilesUsed will return a list of all the configuration files that exist within the specified search space. This are the same files used when calling ReadConfig.

func Get

func Get(key string) interface{}

Get will get a variable by key

func GetBool

func GetBool(key string) bool

GetBool will get the boolean value at the given key

func GetBoolErr

func GetBoolErr(key string) (bool, error)

GetBoolErr will get a boolean value but return an error is something went wrong.

func GetConfig

func GetConfig() interface{}

GetConfig will return the the config struct that has been set by the user but as an interface type.

func GetErr

func GetErr(key string) (interface{}, error)

GetErr will get the value stored at some key and return an error if something went wrong.

func GetFloat

func GetFloat(key string) float64

func GetFloat32

func GetFloat32(key string) float32

func GetFloat32Err added in v0.1.3

func GetFloat32Err(key string) (float32, error)

func GetFloat64 added in v0.1.3

func GetFloat64(key string) float64

func GetFloat64Err added in v0.1.3

func GetFloat64Err(key string) (float64, error)

func GetFloatErr added in v0.1.3

func GetFloatErr(key string) (float64, error)

func GetInt

func GetInt(key string) int

GetInt will get the int value of a key

func GetInt32 added in v0.1.3

func GetInt32(key string) int32

func GetInt32Err added in v0.1.3

func GetInt32Err(key string) (int32, error)

func GetInt64 added in v0.1.3

func GetInt64(key string) int64

func GetInt64Err added in v0.1.3

func GetInt64Err(key string) (int64, error)

func GetInt64Slice

func GetInt64Slice(key string) []int64

GetInt64Slice will return a slice of int64.

Warning: will panic if the key given does not reference a []int64

func GetIntErr

func GetIntErr(key string) (int, error)

GetIntErr will return an get an int but also return an error if something went wrong, main just missing keys and conversion errors

func GetIntSlice

func GetIntSlice(key string) []int

GetIntSlice will get a slice of ints from a key

func GetString

func GetString(key string) string

GetString will get the config value by name and return it as a string

func GetStringErr

func GetStringErr(key string) (string, error)

GetStringErr is the same as get string but it returns an error when something went wrong, mainly if the key does not exist

func GetStringMap

func GetStringMap(key string) map[string]string

GetStringMap will get a map of string keys to string values

func GetUint added in v0.1.3

func GetUint(key string) uint

func GetUint32 added in v0.1.3

func GetUint32(key string) uint32

func GetUint32Err added in v0.1.3

func GetUint32Err(key string) (uint32, error)

func GetUint64 added in v0.1.3

func GetUint64(key string) uint64

func GetUint64Err added in v0.1.3

func GetUint64Err(key string) (uint64, error)

func GetUintErr added in v0.1.3

func GetUintErr(key string) (uint, error)

func Getenv added in v0.0.2

func Getenv(key string) string

Getenv wraps GetString with os.ExpandEnv

func HasKey

func HasKey(key string) bool

HasKey tests if the config struct has a key given

func HomeDir added in v0.0.2

func HomeDir() string

HomeDir will get the user's home directory

func InitDefaults added in v0.1.0

func InitDefaults() error

InitDefaults will find all the default values and set each struct field accordingly.

func IsEmpty

func IsEmpty(key string) bool

IsEmpty returns true if the value stored at some key is a zero value or an empty value

func NewConfigCommand added in v0.0.2

func NewConfigCommand() *cobra.Command

NewConfigCommand creates a new cobra command for configuration

func Paths added in v0.1.0

func Paths() []string

Paths returns the slice of folder paths that will be searched when looking for a config file.

func PathsUsed added in v0.1.4

func PathsUsed() []string

PathsUsed will return all configuration paths where there is an existing configuration file.

func ReadConfig added in v0.1.2

func ReadConfig() error

ReadConfig will read all the config files.

If multiple config files are found, then the first ones found will have the highest precedence and the following config files will not overwrite existing values.

func ReadConfigFile deprecated

func ReadConfigFile() error

Deprecated: use ReadConfig

func ReadConfigFromFile deprecated added in v0.1.3

func ReadConfigFromFile(filepath string) error

Deprecated: Use AddFilepath

func ReadConfigNoOverwrite added in v0.1.4

func ReadConfigNoOverwrite() error

ReadConfigNoOverwrite will read all config files but will not overwrite fields on the config struct if they are not a zero value.

func RemoveFile added in v0.1.4

func RemoveFile(name string)

RemoveFile will remove a filename from the list of config files names. Essentially the inverse operation of AddFilename.

func RemovePath added in v0.1.4

func RemovePath(path string)

RemovePath will remove a path from the list of possible config file locations.

func SetConfig

func SetConfig(conf interface{}) error

SetConfig will set the config struct

func SetFilename deprecated

func SetFilename(name string)

Deprecated: Use AddFile

func SetNestedFlagDelim added in v0.1.2

func SetNestedFlagDelim(delim rune)

SetNestedFlagDelim changed the character used to seperate the names of nested flags.

func SetType

func SetType(ext string) error

SetType will set the file type of config being used.

func Updated added in v0.1.2

func Updated() (<-chan struct{}, error)

Updated will return a channel which will never close and will recieve an empty struct every time a config file is created, or written to.

func Watch added in v0.1.2

func Watch() error

Watch will watch the config files and reload the config data whenever one of the files is created, or changes.

Types

type Config

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

Config holds configuration metadata

func New

func New(conf interface{}) *Config

New creates a new config object from a configuration struct.

func (*Config) AddFile added in v0.1.2

func (c *Config) AddFile(name string)

AddFile will add a filename to the list of possible config filenames. This should be the name of a file without any information about the directory or location.

A path and filename could be used and will be treated as relative to any of the paths added with AddPath but is behavior which is not guaranteed to be supported in the future.

To add a directory to the search path, use AddPath.

func (*Config) AddFilepath added in v0.1.4

func (c *Config) AddFilepath(filepath string)

AddFilepath will add a full filepath to the list of possible config files. This is not the same as adding the path and filename separately. This does not add a search path or filename to search for and should be regarded as hard coding a configuration filepath.

func (*Config) AddPath

func (c *Config) AddPath(path string)

AddPath will add a path the the list of possible configuration folders where a file could be found. See AddFile to add a file to the list of possible files to be read within a configuration search path.

func (*Config) AddUserConfigDir added in v0.1.3

func (c *Config) AddUserConfigDir(dirname string) error

AddUserConfigDir will add a config dir using the user config dir (see os.UserConfigDir) and join it with the name given.

$XDG_CONFIG_DIR/<dirname>

func (*Config) AddUserHomeDir added in v0.1.3

func (c *Config) AddUserHomeDir(name string) error

AddUserHomeDir will add a config dir using the user home dir (see os.UserHomeDir) and join it with the name given and a "."

$HOME/.<name>

func (*Config) BindToFlagSet added in v0.1.0

func (c *Config) BindToFlagSet(set *flag.FlagSet, resolvers ...FlagInfo)

BindToFlagSet will bind the config struct to a standard library flag set

func (*Config) BindToPFlagSet added in v0.1.0

func (c *Config) BindToPFlagSet(set *pflag.FlagSet, resolvers ...FlagInfo)

BindToPFlagSet will bind the config object to a pflag set. See https://pkg.go.dev/github.com/spf13/pflag?tab=doc

func (*Config) DirUsed deprecated

func (c *Config) DirUsed() string

Deprecated: use PathsUsed

func (*Config) FileUsed deprecated

func (c *Config) FileUsed() string

Deprecated: use FilesUsed

func (*Config) FilesUsed added in v0.1.4

func (c *Config) FilesUsed() []string

FilesUsed will return a list of all the configuration files that exist within the specified search space. This are the same files used when calling ReadConfig.

func (*Config) Get

func (c *Config) Get(key string) interface{}

Get will get a variable by key

func (*Config) GetBool

func (c *Config) GetBool(key string) bool

GetBool will get the boolean value at the given key

func (*Config) GetBoolErr

func (c *Config) GetBoolErr(key string) (bool, error)

GetBoolErr will get a boolean value but return an error is something went wrong.

func (*Config) GetConfig

func (c *Config) GetConfig() interface{}

GetConfig will return the the config struct that has been set by the user but as an interface type.

func (*Config) GetErr

func (c *Config) GetErr(key string) (interface{}, error)

GetErr will get the value stored at some key and return an error if something went wrong.

func (*Config) GetFloat

func (c *Config) GetFloat(key string) float64

func (*Config) GetFloat32

func (c *Config) GetFloat32(key string) float32

func (*Config) GetFloat32Err added in v0.1.3

func (c *Config) GetFloat32Err(key string) (float32, error)

func (*Config) GetFloat64 added in v0.1.3

func (c *Config) GetFloat64(key string) float64

func (*Config) GetFloat64Err added in v0.1.3

func (c *Config) GetFloat64Err(key string) (float64, error)

func (*Config) GetFloatErr added in v0.1.3

func (c *Config) GetFloatErr(key string) (float64, error)

func (*Config) GetInt

func (c *Config) GetInt(key string) int

GetInt will get the int value of a key

func (*Config) GetInt32 added in v0.1.3

func (c *Config) GetInt32(key string) int32

func (*Config) GetInt32Err added in v0.1.3

func (c *Config) GetInt32Err(key string) (int32, error)

func (*Config) GetInt64 added in v0.1.3

func (c *Config) GetInt64(key string) int64

func (*Config) GetInt64Err added in v0.1.3

func (c *Config) GetInt64Err(key string) (int64, error)

func (*Config) GetInt64Slice

func (c *Config) GetInt64Slice(key string) []int64

GetInt64Slice will return a slice of int64.

Warning: will panic if the key given does not reference a []int64

func (*Config) GetIntErr

func (c *Config) GetIntErr(key string) (int, error)

GetIntErr will return an get an int but also return an error if something went wrong, main just missing keys and conversion errors

func (*Config) GetIntSlice

func (c *Config) GetIntSlice(key string) []int

GetIntSlice will get a slice of ints from a key

Warning: will panic if the key does not reference a []int

func (*Config) GetString

func (c *Config) GetString(key string) string

GetString will get the config value by name and return it as a string. This function will also expand any environment variables in the value returned.

func (*Config) GetStringErr

func (c *Config) GetStringErr(key string) (string, error)

GetStringErr is the same as get string but it returns an error when something went wrong, mainly if the key does not exist

func (*Config) GetStringMap

func (c *Config) GetStringMap(key string) map[string]string

GetStringMap will get a map of string keys to string values

func (*Config) GetUint added in v0.1.3

func (c *Config) GetUint(key string) uint

func (*Config) GetUint32 added in v0.1.3

func (c *Config) GetUint32(key string) uint32

func (*Config) GetUint32Err added in v0.1.3

func (c *Config) GetUint32Err(key string) (uint32, error)

func (*Config) GetUint64 added in v0.1.3

func (c *Config) GetUint64(key string) uint64

func (*Config) GetUint64Err added in v0.1.3

func (c *Config) GetUint64Err(key string) (uint64, error)

func (*Config) GetUintErr added in v0.1.3

func (c *Config) GetUintErr(key string) (uint, error)

func (*Config) Getenv added in v0.0.2

func (c *Config) Getenv(key string) string

Getenv wraps GetString with os.ExpandEnv

func (*Config) HasKey

func (c *Config) HasKey(key string) bool

HasKey tests if the config struct has a key given

func (*Config) InitDefaults added in v0.1.0

func (c *Config) InitDefaults() error

InitDefaults will find all the default values and set each struct field accordingly.

func (*Config) IsEmpty

func (c *Config) IsEmpty(key string) bool

IsEmpty returns true if the value stored at some key is a zero value or an empty value

func (*Config) NewConfigCommand added in v0.1.4

func (c *Config) NewConfigCommand() *cobra.Command

func (*Config) Paths added in v0.1.0

func (c *Config) Paths() []string

Paths returns the slice of folder paths that will be searched when looking for a config file.

func (*Config) PathsUsed added in v0.1.4

func (c *Config) PathsUsed() []string

PathsUsed will return all configuration paths where there is an existing configuration file.

func (*Config) ReadConfig added in v0.1.2

func (c *Config) ReadConfig() error

ReadConfig will read all the config files.

If multiple config files are found, then the first ones found will have the highest precedence and the following config files will not overwrite existing values.

func (*Config) ReadConfigFile deprecated

func (c *Config) ReadConfigFile() error

Deprecated: use ReadConfig

func (*Config) ReadConfigFromFile deprecated added in v0.1.3

func (c *Config) ReadConfigFromFile(filepath string) error

Deprecated: Use AddFilepath

func (*Config) ReadConfigNoOverwrite added in v0.1.4

func (c *Config) ReadConfigNoOverwrite() error

ReadConfigNoOverwrite will read all config files but will not overwrite fields on the config struct if they are not a zero value.

func (*Config) ReloadOn added in v0.1.3

func (c *Config) ReloadOn(sig ...os.Signal)

ReloadOn takes a list of signals and will reload the config whenever any of them are received.

func (*Config) RemoveFile added in v0.1.4

func (c *Config) RemoveFile(name string)

RemoveFile will remove a filename from the list of config files names. Essentially the inverse operation of AddFilename.

func (*Config) RemovePath added in v0.1.4

func (c *Config) RemovePath(path string)

RemovePath will remove a path from the list of possible config file locations.

func (*Config) SetConfig

func (c *Config) SetConfig(conf interface{}) error

SetConfig will set the config struct

func (*Config) SetFilename deprecated

func (c *Config) SetFilename(name string)

Deprecated: Use AddFile

func (*Config) SetType

func (c *Config) SetType(t string) error

SetType will set the file type of config being used.

func (*Config) Updated added in v0.1.2

func (c *Config) Updated() (<-chan struct{}, error)

Updated will return a channel which will never close and will recieve an empty struct every time a config file is created, or written to.

func (*Config) UseDefaultDirs

func (c *Config) UseDefaultDirs(dirname string)

UseDefaultDirs sets the config and home directories as possible config dir options.

If the config dir is found (see os.UserConfigDir) then "<config dir>/<name>" is added to the list of possible config paths. If the home dir is found (see os.UserHomeDir) then "<home dir>/.<name>" is added to the list of possible config paths.

These paths are added the list (its different for windows)

$XDG_CONFIG_DIR/<name>
$HOME/.<name>

func (*Config) Watch added in v0.1.2

func (c *Config) Watch() error

Watch will watch the config files and reload the config data whenever one of the files is created, or changes.

type Flag added in v0.1.4

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

func (*Flag) IsFlag added in v0.1.4

func (f *Flag) IsFlag() bool

func (*Flag) Name added in v0.1.4

func (f *Flag) Name() string

func (*Flag) Shorthand added in v0.1.4

func (f *Flag) Shorthand() string

func (*Flag) Usage added in v0.1.4

func (f *Flag) Usage() string

type FlagInfo added in v0.1.4

type FlagInfo interface {
	Name() string
	Usage() string
	Shorthand() string
	IsFlag() bool
}

func DisableFlag added in v0.1.4

func DisableFlag(name string) FlagInfo

func NewFlagInfo added in v0.1.4

func NewFlagInfo(name, shorthand, usage string) FlagInfo

Jump to

Keyboard shortcuts

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