Go cheatsheet - Env
Env
Functions to operate environment variables:
os.Getenv
: get env variable by name, if not set, return empty stringos.LookupEnv
: return (value, exists)os.Setenv
: set env variable valueos.Unsetenv
: Unset env variable
Sample code:
package main
import (
"fmt"
"os"
)
func main() {
dbConn := os.Getenv("DB_CONN")
fmt.Println("DB Conn:", dbConn)
dbConn, exists := os.LookupEnv("DB_CONN")
if !exists {
fmt.Println("Env is not set")
} else {
fmt.Println("DB Conn:", dbConn)
}
os.Setenv("DB_CONN", "mongodb://abc")
dbConn = os.Getenv("DB_CONN")
fmt.Println("DB Conn:", dbConn) // mongodb://abc
os.Unsetenv("DB_CONN")
}