Table Of Contents
The env package provides a convenient interface for loading environment and property files.
package main
import (
"github.com/reglue4go/env"
)
func main() {
items := env.Read("DB_DATABASE=:memory:\nDB_PORT=3306")
props := env.ReadProperties(
"app.name=Go",
"db.port=3306\nhost:localhost",
"DB_DATABASE=:memory:\nDB_PORT=3306",
"./app.properties",
)
value := items.Get("DB_PORT").ToInt()
fmt.Printf("%v\n", value) // 3306
value := props.MustGetString("host")
fmt.Printf("%v\n", value) // "localhost"
}
… | … | … |
---|---|---|
Fill | Get | GetFluent |
Load | LoadRemote | Read |
ReadProperties | ReadRemote | Set |
The Set method adds a key value pair environment variable:
env.Set("USER", "bob")
env.Set("API_KEY", "e5akemy")
The ReadRemote method reads values from io.Reader in to a Bag(map):
if response, err := http.Get("https://website.com/config/.env.production"); err == nil {
var items := env.ReadRemote(response.Body)
value := items.Get("DB_PORT").ToInt()
// 3306
}
The ReadProperties method reads values from files, plain strings and io.Reader in to a Bag(map):
var props := env.ReadProperties(
"app.name=Go",
"db.port=3306\nhost:localhost",
"DB_DATABASE=:memory:\nDB_PORT=3306",
"./app.properties",
)
value := props.MustGetString("DB_DATABASE")
// ":memory:"
The Read method reads values from a file or plain string in to a Bag(map):
var items := env.Read("DB_DATABASE=:memory:\nDB_PORT=3306")
value := items.Get("DB_PORT").ToInt()
// 3306
The LoadRemote method reads values from an io.Reader in to environment variables:
if response, err := http.Get("https://website.com/config/.env.production"); err == nil {
env.Load(response.Body)
}
The Load method reads values from a file or plain string in to environment variables:
env.Load() // loads default .env
env.Load("DB_DATABASE=:memory:\nDB_PORT=3306") // loads plain string
env.Load("./env.local") // loads file
The GetFluent method retrieves the environment variable as a Fluent value:
value := env.GetFluent("HTTP_PORT").ToInt()
// 80
The Get method retrieves the environment variable as a string:
value := env.Get("HTTP_PORT")
// "80"
The Fill method populates environment variables from a given map:
env.Fill(map[string]string{
"HTTP_PORT": "80",
"APP_NAME": "recipes",
})
This package has been tested on the following platforms.
golang | ubuntu | macos | windows |
---|---|---|---|
1.18.x | ✓ | ✓ | ✓ |
1.20.x | ✓ | ✓ | ✓ |
1.22.x | ✓ | ✓ | ✓ |