DotEnv
GoLobby DotEnv is a lightweight package for loading dot env (.env) files into structs for Go projects
Documentation
Supported Versions
It requires Go v1.11
or newer versions.
Installation
To install this package run the following command in the root of your project.
go get github.com/golobby/dotenv
Usage Example
Sample .env
file:
DEBUG=true
APP_NAME=MyApp
APP_PORT=8585
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"`
}
}
config := Config{}
file, err := os.Open(".env")
err = dotenv.NewDecoder(file).Decode(&config)
// Use `config` struct in your app!
Usage Tips
- 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.
Field Types
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
See Also
- 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
License
GoLobby DotEnv is released under the MIT License.