import"github.com/kelseyhightower/envconfig"See godoc
Set some environment variables:
export MYAPP_DEBUG=false
export MYAPP_PORT=8080
export MYAPP_USER=Kelsey
export MYAPP_RATE="0.5"Write some code:
package main
import (
"fmt""log""github.com/kelseyhightower/envconfig"
)
typeSpecificationstruct {
DebugboolPortintUserstringRatefloat32
}
funcmain() {
varsSpecificationerr:=envconfig.Process("myapp", &s)
iferr!=nil {
log.Fatal(err.Error())
}
format:="Debug: %v\nPort: %d\nUser: %s\nRate: %f\n"_, err=fmt.Printf(format, s.Debug, s.Port, s.User, s.Rate)
iferr!=nil {
log.Fatal(err.Error())
}
}Results:
Debug: false
Port: 8080
User: Kelsey
Rate: 0.500000export MYAPP_KEYS=key1,key2,key3package main
import (
"fmt""log""reflect""strings""github.com/kelseyhightower/envconfig"
)
typeSpecificationstruct {
Keys []string
}
funcmain() {
varsSpecificationenvconfig.RegisterDecoder("Keys", func(valuestring, fieldValue, struc reflect.Value) error {
items:=strings.Split(value, ",")
n:=len(items)
iffieldValue.Len() <n {
fieldValue.Set(reflect.MakeSlice(fieldValue.Type(), n, n))
}
fori, v:=rangeitems {
fieldValue.Index(i).SetString(v)
}
returnnil
})
deferenvconfig.ClearDecoders()
err:=envconfig.Process("myapp", &s)
iferr!=nil {
log.Fatal(err.Error())
}
format:="Keys: %v"_, err=fmt.Printf(format, s.Keys)
iferr!=nil {
log.Fatal(err.Error())
}
}Keys: [key1 key2 key3]Envconfig supports the use of struct tags to specify alternate environment variables.
For example, consider the following struct:
typeSpecificationstruct {
MultiWordVar`envconfig:"multi_word_var"`
}Whereas before, the value for MultiWordVar would have been populated
with MYAPP_MULTIWORDVAR, it will now be populated with
MYAPP_MULTI_WORD_VAR.
export MYAPP_MULTI_WORD_VAR="this will be the value"# export MYAPP_MULTIWORDVAR="and this will not"