Access environment variables from Go, and populate structs from them.
Import path is go.deanishe.net/env
.
You can directly access environment variables, or populate your structs from them using struct tags and env.Bind()
.
Read int
, float64
, duration
and string
values from environment variables, with optional fallback values for unset variables.
import "go.deanishe.net/env"
// Get value for key or return empty string
s := env.Get("SHELL")
// Get value for key or return a specified default
s := env.Get("DOES_NOT_EXIST", "fallback value")
// Get an int (or 0 if SOME_NUMBER is unset or empty)
i := env.GetInt("SOME_NUMBER")
// Int with a fallback
i := env.GetInt("SOME_UNSET_NUMBER", 10)
You can also populate a struct directly from the environment by appropriately tagging it and calling env.Bind()
:
// Simple configuration struct
type config struct {
HostName string `env:"HOSTNAME"` // default would be HOST_NAME
Port int // leave as default (PORT)
SSL bool `env:"USE_SSL"` // default would be SSL
Online bool `env:"-"` // ignore this field
}
// Set some values in the environment for test purposes
os.Setenv("HOSTNAME", "api.example.com")
os.Setenv("PORT", "443")
os.Setenv("USE_SSL", "1")
os.Setenv("ONLINE", "1") // will be ignored
// Create a config and bind it to the environment
c := &config{}
if err := Bind(c); err != nil {
// handle error...
}
// config struct now populated from the environment
fmt.Println(c.HostName)
fmt.Printf("%d\n", c.Port)
fmt.Printf("%v\n", c.SSL)
fmt.Printf("%v\n", c.Online)
// Output:
// api.example.com
// 443
// true
// false
Variables are retrieved via implementors of the env.Env
interface (which env.Bind()
accepts as a second, optional parameter):
type Env interface {
// Lookup retrieves the value of the variable named by key.
//
// It follows the same semantics as os.LookupEnv(). If a variable
// is unset, the boolean will be false. If a variable is set, the
// boolean will be true, but the variable may still be an empty
// string.
Lookup(key string) (string, bool)
}
So you can pass a custom Env
implementation to Bind()
in order to populate structs from a source other than environment variables.
See _examples/docopt to see how to implement a custom Env
that populates a struct from docopt
command-line options.
Dump a struct to a map[string]string by passing it to Dump():
type options struct {
Hostname string
Port int
}
o := options{
Hostname: "www.example.com",
Port: 22,
}
vars, err := Dump(o)
if err != nil {
// handler err
}
fmt.Println(vars["HOSTNAME"]) // -> www.example.com
fmt.Println(vars["PORT"]) // -> 22
go get go.deanishe.net/env
Read the documentation on GoDoc.
This library is released under the MIT Licence.