This is a tiny package to map the environment variables to Go structs w/o the need of a config file. It supports prefixing, nesting and default values in your config structs. Please check out the examples below.
-
string -
int,Uint,int8,Uint8,int16,Uint16,int32,Uint32,int64,Uint64 -
float32,float64 -
bool -
[]string -
[]int,[]int64 -
[]float32,[]float64
go get github.com/orkungursel/go-ecopackage main
import (
"fmt"
"github.com/orkungursel/go-eco"
)
type Config struct {
Port int `env:"PORT" default:"8080"`
Host string `env:"HOST" default:"localhost"`
}
func main() {
config := Config{}
if err := eco.Unmarshal(&config); err != nil {
panic(err)
}
fmt.Printf("%+v\n", config)
}$ PORT=8081 go run main.go
{Port:8081 Host:localhost}...
config := Config{}
e := eco.New()
e.SetPrefix("APP")
if err := e.Unmarshal(&config); err != nil {
panic(err)
}
...$ APP_PORT=8081 go run main.go
{Port:8081 Host:localhost}package main
import (
"fmt"
"github.com/orkungursel/go-eco"
)
type Config struct {
Port int `env:"PORT" default:"8080"`
Host string `env:"HOST" default:"localhost"`
Logger struct {
Level string `env:"LEVEL" default:"info"`
}
}
func main() {
config := Config{}
if err := eco.Unmarshal(&config); err != nil {
panic(err)
}
fmt.Printf("%+v\n", config)
}$ PORT=8081 LOGGER_LEVEL=debug go run main.go
{Port:8081 Host:localhost Logger: {Level:debug}}func SetPrefix(prefix string)SetPrefix sets the prefix for the environment variables.
By default, the prefix is empty.
Example
...
func main() {
config := Config{}
if err := eco.SetPrefix("custom_prefix").Unmarshal(&config); err != nil {
panic(err)
}
fmt.Printf("%+v\n", config)
}$ CUSTOM_PREFIX_PORT=8081 go run main.go
{Port:8081 Host:localhost}func SetArraySeparator(sep string)SetArraySeparator sets the separator for array values.
By default, the separator is `,`.
Example
package main
import (
"fmt"
"github.com/orkungursel/go-eco"
)
type Config struct {
Foo []string `default:"foo,bar,baz"`
}
func main() {
config := Config{}
if err := eco.SetArraySeparator(",").Unmarshal(&config); err != nil {
panic(err)
}
fmt.Printf("%+v\n", config)
}func SetEnvNameSeparator(envNameSeparator string) *eco {SetEnvNameSeparator sets the separator for the environment variable names.
By default, the separator is `_`.
Example
package main
import (
"fmt"
"github.com/orkungursel/go-eco"
)
type Config struct {
Sub struct {
Foo string
}
}
func main() {
config := Config{}
if err := eco.SetEnvNameSeparator("__").Unmarshal(&config); err != nil {
panic(err)
}
fmt.Printf("%+v\n", config)
}$ SUB__FOO=bar go run main.go
{Sub: {Foo:bar}}func Unmarshal(v interface{}) errorUnmarshal takes a pointer to a struct and unmarshals the environment variables to the struct.
This project is licensed under the MIT License.