env

package
v0.111.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 29, 2026 License: Apache-2.0 Imports: 12 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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

Examples

Constants

View Source
const Redacted = "[redacted]"

Redacted replaces a sensitive value.

Variables

View Source
var Default = NewRegistry()

Default is the registry packages declare into.

Functions

func Bool

func Bool(name string, defaultVal bool) 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

func Duration(name string, defaultVal time.Duration) time.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

func Float64(name string, defaultVal float64) 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

func Int(name string, defaultVal int) 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

func Int64(name string, defaultVal int64) 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

func MustDuration(name string) time.Duration

MustDuration returns the time.Duration value of the named environment variable. Exits 1 if unset or not parseable.

func MustInt

func MustInt(name string) int

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

func MustString(name string) string

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

func String(name, defaultVal string) string

String returns the value of the named environment variable, or defaultVal if it is unset or empty.

func Strings

func Strings(name, sep string, defaultVal []string) []string

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)

func UnsetEnv

func UnsetEnv(name string) func()

UnsetEnv clears name and returns a cleanup function that restores it.

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 Kind

type Kind string

Kind is what a variable's value must parse as.

const (
	KindString   Kind = "string"
	KindBool     Kind = "bool"
	KindInt      Kind = "int"
	KindFloat    Kind = "float"
	KindDuration Kind = "duration"
	KindList     Kind = "list" // comma-separated
)

Kinds.

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 NewRegistry

func NewRegistry() *Registry

NewRegistry returns an empty registry.

func (*Registry) Check

func (r *Registry) Check() int

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

func (r *Registry) Declare(v Var) *Var

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

func (r *Registry) Handler() http.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

func (r *Registry) Removed(name, since, advice string) Removal

Removed records that name was removed in release since; advice says what to do.

func (*Registry) RemovedList

func (r *Registry) RemovedList() []Removal

RemovedList returns the removed variables recorded in the registry, sorted by name.

func (*Registry) Snapshot

func (r *Registry) Snapshot(environ []string) []Info

Snapshot lists every declared variable, sorted by name, with its value taken from environ. Sensitive values are redacted.

func (*Registry) Validate

func (r *Registry) Validate(environ []string) []Problem

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

func Removed(name, since, advice string) Removal

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.

func Declare

func Declare(v Var) *Var

Declare registers v in the Default registry and returns the stored variable.

func (*Var) Lookup

func (v *Var) Lookup() (string, bool)

Lookup is os.LookupEnv by declared name.

func (*Var) Owner

func (v *Var) Owner() string

Owner is the package that declared the variable.

func (*Var) Validate

func (v *Var) Validate(val string) error

Validate reports whether val is acceptable for the variable: it must parse as Kind and pass Check. Registry.Validate applies it to every variable that is set.

func (*Var) Value

func (v *Var) Value() string

Value returns the variable's value, "" if unset: os.Getenv by declared name.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL