package main
import (
"fmt"
"log"
"time"
"github.com/codingconcepts/env"
)
type config struct {
Secret []byte `env:"SECRET" required:"true"`
Region string `env:"REGION"`
Port int `env:"PORT" required:"true"`
Peers []string `env:"PEERS"` // you can use `delimiter` tag to specify separator, for example `delimiter:" "`
ConnectionTimeout time.Duration `env:"TIMEOUT" default:"10s"`
}
func main() {
c := config{}
if err := env.Set(&c); err != nil {
log.Fatal(err)
}
...
}
$ ID=1 SECRET=shh PORT=1234 PEERS=localhost:1235,localhost:1236 TIMEOUT=5s go run main.go
Package env makes satisfying factor III of the 12-factor methodology easy, by allowing struct fields to be populated directly from environment
variables with the use of struct tags.
To use, create a struct tag called "env" and call env.Set, passing a pointer
to the struct you wish to populate. You can optionally, provide a "required"
tag to determine whether an error should be returned in the event of missing
environment configuration.
Like the encoding/* packages, env.Set will return an error if a non-pointer
type is provided.
SetPrefix sets the fields of a struct from environment config
with a given prefix. If a field is unexported or required
configuration is not found, an error will be returned.