Documentation
¶
Overview ¶
Package env provides typed, zero-dependency helpers for reading environment variables with defaults, required-or-fatal semantics, and common Go types (bool, int, duration, slice).
Every fleet service needs at least a dozen env knobs. Without a shared layer each service re-implements os.Getenv + strconv + log.Fatal, each subtly differently. This package collapses that into one place with consistent error messages and a testable override path (SetEnv / UnsetEnv in tests).
Usage:
port := env.String("PORT", "8080")
enabled := env.Bool("GRAPH_ENABLED", true)
timeout := env.Duration("SELFTEST_TIMEOUT", 5*time.Second)
workers := env.Int("WORKER_COUNT", 4)
url := env.MustString("APIKEY_SERVICE_URL") // fatal if unset
Example ¶
Typed readers with a default replace the strconv boilerplate; an unset or unparsable variable falls back to the default.
package main
import (
"fmt"
"os"
"time"
"github.com/baditaflorin/go-common/env"
)
func main() {
_ = os.Setenv("EXAMPLE_PORT", "8080")
_ = os.Setenv("EXAMPLE_VERBOSE", "true")
_ = os.Setenv("EXAMPLE_TIMEOUT", "250ms")
defer func() {
_ = os.Unsetenv("EXAMPLE_PORT")
_ = os.Unsetenv("EXAMPLE_VERBOSE")
_ = os.Unsetenv("EXAMPLE_TIMEOUT")
}()
fmt.Println(env.Int("EXAMPLE_PORT", 80))
fmt.Println(env.Bool("EXAMPLE_VERBOSE", false))
fmt.Println(env.Duration("EXAMPLE_TIMEOUT", 5*time.Second))
fmt.Println(env.String("EXAMPLE_NOT_SET", "fallback"))
}
Output: 8080 true 250ms fallback
Index ¶
- Constants
- Variables
- func Bool(name string, defaultVal bool) bool
- func Duration(name string, defaultVal time.Duration) time.Duration
- func Float64(name string, defaultVal float64) float64
- func Int(name string, defaultVal int) int
- func Int64(name string, defaultVal int64) int64
- func MustDuration(name string) time.Duration
- func MustInt(name string) int
- func MustString(name string) string
- func Require(names ...string)
- func SetEnv(name, value string) func()
- func String(name, defaultVal string) string
- func Strings(name, sep string, defaultVal []string) []string
- func UnsetEnv(name string) func()
- type Info
- type Kind
- type Problem
- type Registry
- func (r *Registry) Check() int
- func (r *Registry) Declare(v Var) *Var
- func (r *Registry) Handler() http.Handler
- func (r *Registry) Removed(name, since, advice string) Removal
- func (r *Registry) RemovedList() []Removal
- func (r *Registry) Snapshot(environ []string) []Info
- func (r *Registry) Validate(environ []string) []Problem
- type Removal
- type Var
Examples ¶
Constants ¶
const Redacted = "[redacted]"
Redacted replaces a sensitive value.
Variables ¶
var Default = NewRegistry()
Default is the registry packages declare into.
Functions ¶
func Bool ¶
Bool returns the boolean value of the named environment variable, or defaultVal if it is unset or empty. Accepted truthy values: "1", "true", "yes", "on" (case-insensitive). Everything else is false.
func Duration ¶
Duration returns the time.Duration value of the named environment variable, or defaultVal if it is unset, empty, or not parseable by time.ParseDuration. Example values: "5s", "100ms", "2m30s".
func Float64 ¶
Float64 returns the float64 value of the named environment variable, or defaultVal if it is unset, empty, or not a valid float.
func Int ¶
Int returns the integer value of the named environment variable, or defaultVal if it is unset, empty, or not a valid integer. Parse errors are logged as warnings but do not crash the process.
func Int64 ¶
Int64 returns the int64 value of the named environment variable, or defaultVal if it is unset, empty, or not a valid integer.
func MustDuration ¶
MustDuration returns the time.Duration value of the named environment variable. Exits 1 if unset or not parseable.
func MustInt ¶
MustInt returns the integer value of the named environment variable. Exits 1 if the variable is unset, empty, or not a valid integer.
func MustString ¶
MustString returns the value of the named environment variable. It calls log.Fatalf and exits 1 if the variable is unset or empty, printing a copy-paste remediation hint.
func Require ¶
func Require(names ...string)
Require panics (not log.Fatal) with a human-readable message when any of the listed env vars is unset or empty. Intended for test helpers and integration test setup where panic is more appropriate than os.Exit.
env.Require("APIKEY_SERVICE_URL", "GRAPH_COLLECTOR_URL")
func SetEnv ¶
func SetEnv(name, value string) func()
SetEnv sets name=value for the duration of a test and returns a cleanup function that restores the previous value (or unsets it). Intended for use in t.Cleanup():
t.Cleanup(env.SetEnv("PORT", "9090"))
func String ¶
String returns the value of the named environment variable, or defaultVal if it is unset or empty.
func Strings ¶
Strings returns a []string by splitting the named environment variable on sep. If the variable is unset or empty, defaultVal is returned. Whitespace is trimmed from each element; empty elements are dropped.
# e.g. ALLOWED_ORIGINS=https://a.com,https://b.com
origins := env.Strings("ALLOWED_ORIGINS", ",", nil)
Types ¶
type Info ¶
type Info struct {
Name string `json:"name"`
Kind Kind `json:"kind"`
Default string `json:"default,omitempty"`
Doc string `json:"doc,omitempty"`
Owner string `json:"owner,omitempty"`
Secret bool `json:"secret,omitempty"`
Set bool `json:"set"`
Value string `json:"value,omitempty"` // redacted for anything sensitive
}
Info describes one variable for a listing.
type Problem ¶
type Problem struct {
Name string `json:"name"`
Level string `json:"level"` // "error": a set value that cannot work; "warning": worth a look
Message string `json:"message"`
}
Problem is something Validate found.
type Registry ¶
type Registry struct {
// contains filtered or unexported fields
}
Registry holds declarations. Default is the process-wide one.
func (*Registry) Check ¶
Check validates the process's own environment, logs each problem and returns how many were errors. It never exits: a mistyped optional variable must not take a service down. Call it once at start-up.
func (*Registry) Declare ¶
Declare registers v and returns the stored variable. Declaring the same variable twice with the same kind, default and secrecy returns the first; a different redeclaration keeps the first and is reported by Validate.
func (*Registry) Handler ¶
Handler serves the registry as JSON: every declared variable with its redacted value, and the problems Validate finds. It is for a debug listener that is not reachable from outside (obs mounts it on its localhost-only server), never for a public route.
func (*Registry) Removed ¶
Removed records that name was removed in release since; advice says what to do.
func (*Registry) RemovedList ¶
RemovedList returns the removed variables recorded in the registry, sorted by name.
func (*Registry) Snapshot ¶
Snapshot lists every declared variable, sorted by name, with its value taken from environ. Sensitive values are redacted.
func (*Registry) Validate ¶
Validate checks environ (KEY=VALUE strings, as os.Environ returns) against the declarations:
- a declared variable that is set must parse as its Kind and pass its Check;
- a removed variable that is still set gets a warning;
- a set variable that is not declared but is one or two edits away from a declared name that shares its first word (GRAPH_COLLECTER_URL for GRAPH_COLLECTOR_URL) gets a warning with the suggestion: a typo is otherwise silent, because the real variable just stays unset;
- conflicting declarations are reported.
An empty value counts as unset, like the readers in this package.
type Removal ¶
type Removal struct{ Name, Since, Advice string }
Removal is the record of a variable that no longer does anything.
func Removed ¶
Removed records, in the Default registry, that name no longer does anything. If it is still set in a process's environment, Validate says so: nobody can otherwise find out who still sets a variable that was removed. It returns the record so it can be declared at package level without an init function:
var _ = env.Removed("OLD_SWITCH", "v0.102.60", "delete it")
type Var ¶
type Var struct {
Name string
Kind Kind
Default string // as the user would write it; shown in docs, never for a secret
Doc string
// Secret hides the value and the default everywhere the registry shows them.
// Declare every credential as Secret. Values that look sensitive are also
// hidden without it (see Redact), as a second line, not a substitute.
Secret bool
// Check validates a value that is set and has already parsed as Kind, for
// rules beyond the kind ("a ratio in (0,1)").
Check func(value string) error
// contains filtered or unexported fields
}
Var is one declared environment variable.