A go package for creating default configuration variables that can be overridden by environment variables.
go get github.com/bjubes/config
Create a struct with fields that match your environment variables, and create an instance set to your defaults.
typeMyConfigstruct { DB_HOSTstringDB_PORTintPRODboolCOOLDOWNfloat64 } varmyConfig config.Configurator=MyConfig{ DB_HOST: "localhost", DB_PORT: 5432, PROD: false, COOLDOWN: 0.3, }
Make your custom struct implements the
Configuratorinterface using the following code (just copy and paste)func (cMyConfig) GetEnvString(fieldstring) string { returnconfig.GetEnvString(c, field) } func (cMyConfig) GetEnvBool(fieldstring) bool { returnconfig.GetEnvBool(c, field) } func (cMyConfig) GetEnvInt(fieldstring) int { returnconfig.GetEnvInt(c, field) } func (cMyConfig) GetEnvFloat(fieldstring) float64 { returnconfig.GetEnvFloat(c, field) }
Retrieve a value using the methods on your config instance
host:=myConfig.GetEnvString("DB_HOST") port:=myConfig.GetEnvInt("DB_PORT") prod:=myConfig.GetEnvBool("PROD") cool:=myConfig.GetEnvFloat("COOLDOWN")
Values will default to what they are set to in the struct instance, but will be overridden by environment variables if they are set. Environment variables must match the type specified. For specifics, see type matching rules below.
Since the myConfig instance has a type of Configurator, none of the public fields are accessible. This forces retrieving values through the GetEnv methods, so you never accidentally grab the default value without checking for the environment variable first.
Fields promoted from embedded structs are fully supported. All GetEnv methods resolve a field name through the same promotion rules as normal Go field access, so it works with a config that embeds another struct:
typeDBConfigstruct {
DB_HOSTstringDB_PORTint
}
typeMyConfigstruct {
DBConfigPRODboolCOOLDOWNfloat64
}
//Configurator implementation and usage remains the samefunc (cMyConfig) GetEnvString(fieldstring) string {
returnconfig.GetEnvString(c, field)
}
host:=myConfig.GetEnvString("DB_HOST")If a field name appears at more than one embedded level, the shallowest definition wins. If two embedded structs provide the same field name at the same depth, the name is ambiguous and the GetEnv methods will panic.
If the environment variable doesn't meet these rules the default value will be used instead.
string - Environment value will be used as long as it is set, even if its an empty string.
bool - Environment value will be used if the value is a bool, as determined by strconv.ParseBool. Accepted values are: 1, t, T, TRUE, true, True, 0, f, F, FALSE, false, False.
int - Environment value will be used if the value is an integer, as determined by strconv.Atoi.
float - Environment value will be used if the value is a float, as determined by strconv.ParseFloat.