go-config allows to initialize configuration in flexible way using from default, file, environment variables value.
Done in three steps:
- init with value from
default
tag - merge with config file if
filepath
is provided - override with environment variables which stored under
envconfig
tag
- json
- Standard types:
bool
,float
,int
(uint
),slice
,string
time.Duration
,time.Time
: full support with aliasesconfig.Duration
,config.Time
- Custom types, slice of custom types
type Server struct {
Addr string `default:"localhost:8080"`
}
type Server struct {
Addr string `envconfig:"SERVER_ADDR"`
}
type Server struct {
Addr string `json:"addr" envconfig:"SERVER_ADDR" default:"localhost:8080"`
}
Default strings separator is comma.
REDIS_ADDR=127.0.0.1:6377,127.0.0.1:6378,127.0.0.1:6379
type Redis struct {
Addrs []string `json:"addrs" envconfig:"REDIS_ADDR" default:"localhost:6378,localhost:6379"`
}
Slice of structs could be parsed from environment by defining envprefix
.
Every ENV group override element stored at index
of slice or append new one.
Sparse slices are not allowed.
var cfg struct {
...
Replicas []Postgres `json:"replicas" envprefix:"REPLICAS"`
...
}
Environment key should has next pattern:
${envprefix}_${index}_${envconfig}
or ${envprefix}_${index}_${StructFieldName}
REPLICAS_0_POSTGRES_USER=replica REPLICAS_2_USER=replica
In case using json file you have to use aliases config.Duration
, config.Time
, that properly unmarshal it self
type NATS struct {
...
ReconnectInterval config.Duration `json:"reconnect_interval" envconfig:"NATS_RECONNECT_INTERVAL" default:"2s"`
}
Otherwise time.Duration
, time.Time
might be used directly:
var cfg struct {
ReadTimeout time.Duration `envconfig:"READ_TIMEOUT" default:"1s"`
WriteTimeout time.Duration `envconfig:"WRITE_TIMEOUT" default:"10s"`
}