GoLobby DotEnv is a lightweight package for loading dot env (.env) files into structs for Go projects
It requires Go v1.16
or newer versions.
To install this package run the following command in the root of your project.
go get github.com/golobby/dotenv
Sample .env
file:
DEBUG=true
APP_NAME=MyApp
APP_PORT=8585
IPS=192.168.0.1,192.168.0.2
IDS=10,11,12,13
DB_NAME=shop
DB_PORT=3306
DB_USER=root
DB_PASS=secret
Sample .go
file:
type Config struct {
Debug bool `env:"DEBUG"`
App struct {
Name string `env:"APP_NAME"`
Port int16 `env:"APP_PORT"`
}
Database struct {
Name string `env:"DB_NAME"`
Port int16 `env:"DB_PORT"`
User string `env:"DB_USER"`
Pass string `env:"DB_PASS"`
}
IPs []string `env:"IPS"`
IDs []int64 `env:"IDS"`
}
config := Config{}
file, err := os.Open(".env")
err = dotenv.NewDecoder(file).Decode(&config)
// Use `config` struct in your app!
- The
Decode()
function gets a pointer of a struct. - It ignores the fields that have no related environment variables in the file.
- It supports nested structs and struct pointers.
GoLobby DotEnv uses the GoLobby Cast package to cast environment variables to related struct field types. Here you can see the supported types:
https://github.com/golobby/cast#supported-types
The following snippet shows a valid dot env file.
String = Hello Dot Env # Comment
# Quotes
Quote1="Quoted message!"
Quote2="You can use ' here"
Quote3='You can use " here'
Quote4="You can use # here"
# Booleans
Bool1 = true
Bool2 = 1 # true
Bool3 = false
Bool4 = 0 # false
# Arrays
Ints = 1,2, 3, 4 , 5 # []int{1, 2, 3, 4, 5}
Strings = a,b, c, d , e # []string{"a", "b", "c", "d", "e"}
Floats = 3.14,9.8, 6.9 # []float32{3.14, 9.8, 6.9}
- GoLobby/Config: A lightweight yet powerful configuration management for Go projects
- GoLobby/Env: A lightweight package for loading OS environment variables into structs for Go projects
GoLobby DotEnv is released under the MIT License.