Documentation
¶
Overview ¶
Package envconf helps to configure Go applications from the process environment, rather than needing to deploy and parse config files. It mimics the API of other popular config packages such as gcfg.
envconf provides a simple and powerful mechanism to parse configuration: it takes a struct and a function of the signature func(string) string and populates the struct. This give the user the flexibility of specifying where the configuration comes from, but the power of type-safe config parsing.
This way administrators don't need to juggle config files around, and large projects don't have to worry about subsystems trying to find their config in the global process state.
envconf allows the package user to define a type matching the config variables they want to pull out of the environment.
Usage ¶
Define a struct literal or an instance of a struct type and call ReadConfigEnv:
var serverConfig struct {
Port int `required:"true"`
Bind string `default:"0.0.0.0"`
}
err := envconf.ReadConfigEnv(&serverConfig)
// Deal with error here
This will look up both PORT and BIND in the process environment and populate them in the config struct - provided that the value found for Port can be parsed as an int.
You can also set a prefix:
err := envconf.ReadConfigEnvPrefix("MYSERVER_", &serverConfig)
This will behave in the same way as above, but will look for the environment variables MYSERVER_PORT and MYSERVER_BIND. This provides a simple way to namespace the environment variables.
Types ¶
Three basic types are supported: int, bool and string. Slices of these types are also supported; this struct is valid:
type AlarmConfig {
DaysOfWeek []int
Addresses []string
Active bool
}
envconf expects comma-separated values for slice types.
Tags ¶
As seen above, envconf understands the "required" and "default" tags. These do what they sound like.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ReadConfig ¶
ReadConfig reads from this getter func into a struct.
Must be passed a struct or a pointer to a struct.
func ReadConfigEnv ¶
func ReadConfigEnv(conf interface{}) error
ReadConfigEnv reads config from the process environment. A shortcut for:
envconf.ReadConfig(conf, os.GetEnv)
Example ¶
os.Setenv("FOO", "hi")
os.Setenv("BAR", "yes")
defer os.Setenv("FOO", "")
defer os.Setenv("BAR", "")
var conf struct {
Foo string
Bar string
}
if err := ReadConfigEnv(&conf); err != nil {
panic(err)
}
fmt.Println(conf.Foo)
fmt.Println(conf.Bar)
Output: hi yes
func ReadConfigEnvPrefix ¶
ReadConfigenvPrefix reads config from the environment with a set prefix on every environment variable.
func ReadConfigMap ¶
ReadConfigMap reads config from this map.
Types ¶
This section is empty.