Documentation
¶
Overview ¶
Package env implements environment variables parsing.
Usage ¶
Define env using env.String(), Bool(), Int(), etc.
This declares an integer env, N, stored in the pointer nEnv, with type *int:
import "github.com/shaj13/env" var nEnv = env.Int("n", 1234, "usage message for env n")
If you like, you can bind the env to a variable using the Var() functions.
var envvar int func init() { env.IntVar(&envvar, "envname", 1234, "usage message for envname") }
Or you can create custom envs that satisfy the Value interface (with pointer receivers) and couple them to env parsing by
env.Var(&envVal, "name", "usage message for name")
For such envs, the default value is just the initial value of the variable.
After all envs are defined, call
env.Parse()
to parse the environment variables into the defined envs.
Envs may then be used directly. If you're using the envs themselves, they are all pointers; if you bind to variables, they're values.
fmt.Println("ip has value ", *ip) fmt.Println("envvar has value ", envvar)
Integer envs accept 1234, 0664, 0x1234 and may be negative. Boolean envs may be:
1, 0, t, f, T, F, true, false, TRUE, FALSE, True, False
Duration envs accept any input valid for time.ParseDuration.
The default set of environment variables (environ) is controlled by top-level functions. The EnvSet type allows one to define independent sets of envs. The methods of EnvSet are analogous to the top-level functions for environ set.
Example ¶
// These examples demonstrate more intricate uses of the env package. package main import ( "errors" "fmt" "strings" "time" "github.com/shaj13/env" ) var _ = species // Example 1: A single string env called "species" with default value "gopher". var species = env.String("species", "gopher", "the species we are studying") // Example 2: A single string var env called "gopher_type". // Must be set up with an init function. var gopherType string func init() { env.StringVar(&gopherType, "gopher_type", "pocket", "the variety of gopher") } // Example 3: A user-defined env type, a slice of durations. type interval []time.Duration // String is the method to format the env's value, part of the env.Value interface. // The String method's output will be used in diagnostics. func (i *interval) String() string { return fmt.Sprint(*i) } // Set is the method to set the env value, part of the env.Value interface. // Set's argument is a string to be parsed to set the env. // It's a comma-separated list, so we split it. func (i *interval) Set(value string) error { if len(*i) > 0 { return errors.New("interval env already set") } for _, dt := range strings.Split(value, ",") { duration, err := time.ParseDuration(dt) if err != nil { return err } *i = append(*i, duration) } return nil } // Define a env to accumulate durations. Because it has a special type, // we need to use the Var function and therefore create the env during // init. var intervalEnv interval func init() { // Tie the environ to the intervalEnv variable and // set a usage message. env.Var(&intervalEnv, "delta_t", "comma-separated list of intervals to use between events") } func main() { // All the interesting pieces are with the variables declared above, but // to enable the env package to see the env defined there, one must // execute, typically at the start of main (not init!): // env.Parse() // We don't run it here because this is not a main function and // the testing suite has already parsed the envs. }
Output:
Example (Struct) ¶
package main import ( "fmt" "github.com/shaj13/env" ) type Config struct { Host string Port string // .... } func main() { cfg := new(Config) es := env.NewEnvSet("app", env.ExitOnError) es.StringVar(&cfg.Host, "host", "localhost", "App host name") es.StringVar(&cfg.Port, "port", "443", "App port") es.Parse([]string{"APP_HOST=env.localhost"}) fmt.Printf(`%s:%s`, cfg.Host, cfg.Port) }
Output: env.localhost:443
Index ¶
- Variables
- func Bool(name string, value bool, usage string) *bool
- func BoolVar(p *bool, name string, value bool, usage string)
- func Duration(name string, value time.Duration, usage string) *time.Duration
- func DurationVar(p *time.Duration, name string, value time.Duration, usage string)
- func Float64(name string, value float64, usage string) *float64
- func Float64Var(p *float64, name string, value float64, usage string)
- func Func(name, usage string, fn func(string) error)
- func Int(name string, value int, usage string) *int
- func Int64(name string, value int64, usage string) *int64
- func Int64Var(p *int64, name string, value int64, usage string)
- func IntVar(p *int, name string, value int, usage string)
- func NEnv() int
- func Parse()
- func Parsed() bool
- func PrintDefaults()
- func Set(name, value string) error
- func String(name string, value string, usage string) *string
- func StringVar(p *string, name string, value string, usage string)
- func TextVar(p encoding.TextUnmarshaler, name string, value encoding.TextMarshaler, ...)
- func Uint(name string, value uint, usage string) *uint
- func Uint64(name string, value uint64, usage string) *uint64
- func Uint64Var(p *uint64, name string, value uint64, usage string)
- func UintVar(p *uint, name string, value uint, usage string)
- func UnquoteUsage(env *Env) (name string, usage string)
- func Var(value Value, name string, usage string)
- func Visit(fn func(*Env))
- func VisitAll(fn func(*Env))
- type Env
- type EnvSet
- func (e *EnvSet) Bool(name string, value bool, usage string) *bool
- func (e *EnvSet) BoolVar(p *bool, name string, value bool, usage string)
- func (e *EnvSet) Duration(name string, value time.Duration, usage string) *time.Duration
- func (e *EnvSet) DurationVar(p *time.Duration, name string, value time.Duration, usage string)
- func (e *EnvSet) ErrorHandling() ErrorHandling
- func (e *EnvSet) Float64(name string, value float64, usage string) *float64
- func (e *EnvSet) Float64Var(p *float64, name string, value float64, usage string)
- func (e *EnvSet) Func(name, usage string, fn func(string) error)
- func (e *EnvSet) Init(prefix string, errorHandling ErrorHandling)
- func (e *EnvSet) Int(name string, value int, usage string) *int
- func (e *EnvSet) Int64(name string, value int64, usage string) *int64
- func (e *EnvSet) Int64Var(p *int64, name string, value int64, usage string)
- func (e *EnvSet) IntVar(p *int, name string, value int, usage string)
- func (e *EnvSet) Lookup(name string) *Env
- func (e *EnvSet) NEnv() int
- func (e *EnvSet) Output() io.Writer
- func (e *EnvSet) Parse(envs []string) error
- func (e *EnvSet) Parsed() bool
- func (e *EnvSet) Prefix() string
- func (e *EnvSet) PrintDefaults()
- func (e *EnvSet) Set(name, value string) error
- func (e *EnvSet) SetOutput(output io.Writer)
- func (e *EnvSet) String(name string, value string, usage string) *string
- func (e *EnvSet) StringVar(p *string, name string, value string, usage string)
- func (e *EnvSet) TextVar(p encoding.TextUnmarshaler, name string, value encoding.TextMarshaler, ...)
- func (e *EnvSet) Uint(name string, value uint, usage string) *uint
- func (e *EnvSet) Uint64(name string, value uint64, usage string) *uint64
- func (e *EnvSet) Uint64Var(p *uint64, name string, value uint64, usage string)
- func (e *EnvSet) UintVar(p *uint, name string, value uint, usage string)
- func (e *EnvSet) Var(value Value, name string, usage string)
- func (e *EnvSet) Visit(fn func(*Env))
- func (e *EnvSet) VisitAll(fn func(*Env))
- type ErrorHandling
- type Getter
- type Value
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var Environ = NewEnvSet("", ExitOnError)
Environ is the default env set, parsed from os.Environ(). The top-level functions such as BoolVar, Parse, and so on are wrappers for the methods of Environ.
var Usage = func() { fmt.Fprintf(Environ.Output(), "Usage of %s:\n", os.Args[0]) PrintDefaults() }
Usage prints a usage message documenting all defined "Environ" envs to Environ's output, which by default is os.Stderr. It is called when an error occurs while parsing envs. The function is a variable that may be changed to point to a custom function. By default it prints a simple header and calls PrintDefaults; for details about the format of the output and how to control it, see the documentation for PrintDefaults. Custom usage functions may choose to exit the program; by default exiting happens anyway as the Environ's error handling strategy is set to ExitOnError.
Functions ¶
func Bool ¶
Bool defines a bool env with specified name, default value, and usage string. The return value is the address of a bool variable that stores the value of the env.
func BoolVar ¶
BoolVar defines a bool env with specified name, default value, and usage string. The argument p points to a bool variable in which to store the value of the env.
func Duration ¶
Duration defines a time.Duration env with specified name, default value, and usage string. The return value is the address of a time.Duration variable that stores the value of the env. The env accepts a value acceptable to time.ParseDuration.
func DurationVar ¶
DurationVar defines a time.Duration env with specified name, default value, and usage string. The argument p points to a time.Duration variable in which to store the value of the env. The env accepts a value acceptable to time.ParseDuration.
func Float64 ¶
Float64 defines a float64 env with specified name, default value, and usage string. The return value is the address of a float64 variable that stores the value of the env.
func Float64Var ¶
Float64Var defines a float64 env with specified name, default value, and usage string. The argument p points to a float64 variable in which to store the value of the env.
func Func ¶
Func defines a env with the specified name and usage string. Each time the env is seen, fn is called with the value of the env. If fn returns a non-nil error, it will be treated as a env value parsing error.
Example ¶
package main import ( "errors" "fmt" "net" "os" "github.com/shaj13/env" ) func main() { es := env.NewEnvSet("Example", env.ContinueOnError) es.SetOutput(os.Stdout) var ip net.IP es.Func("IP", "`net.IP` to parse", func(s string) error { ip = net.ParseIP(s) if ip == nil { return errors.New("could not parse IP") } return nil }) es.Parse([]string{"EXAMPLE_IP=127.0.0.1"}) fmt.Printf("{ip: %v, loopback: %t}\n\n", ip, ip.IsLoopback()) // 256 is not a valid IPv4 component es.Parse([]string{"EXAMPLE_IP=256.0.0.1"}) fmt.Printf("{ip: %v, loopback: %t}\n\n", ip, ip.IsLoopback()) }
Output: {ip: 127.0.0.1, loopback: true} invalid value "256.0.0.1" for env IP: could not parse IP Usage of Example: EXAMPLE_IP net.IP net.IP to parse {ip: <nil>, loopback: false}
func Int ¶
Int defines an int env with specified name, default value, and usage string. The return value is the address of an int variable that stores the value of the env.
func Int64 ¶
Int64 defines an int64 env with specified name, default value, and usage string. The return value is the address of an int64 variable that stores the value of the env.
func Int64Var ¶
Int64Var defines an int64 env with specified name, default value, and usage string. The argument p points to an int64 variable in which to store the value of the env.
func IntVar ¶
IntVar defines an int env with specified name, default value, and usage string. The argument p points to an int variable in which to store the value of the env.
func Parse ¶
func Parse()
Parse parses the "Environ" envs from os.Environ(). Must be called after all envs are defined and before envs are accessed by the program.
func PrintDefaults ¶
func PrintDefaults()
PrintDefaults prints, to standard error unless configured otherwise, a usage message showing the default settings of all defined envs. For an integer valued env x, the default output has the form
X int usage-message-for-x (default 7)
The usage message will appear on a the same line for anything. The parenthetical default is omitted if the default is the zero value for the type. The listed type, here int, can be changed by placing a back-quoted name in the env's usage string; the first such item in the message is taken to be a parameter name to show in the message and the back quotes are stripped from the message when displayed. For instance, given
env.String("DIR", "", "search `directory` for include files")
the output will be
DIR directory search directory for include files.
To change the destination for env messages, call Environ.SetOutput.
func String ¶
String defines a string env with specified name, default value, and usage string. The return value is the address of a string variable that stores the value of the env.
func StringVar ¶
StringVar defines a string env with specified name, default value, and usage string. The argument p points to a string variable in which to store the value of the env.
func TextVar ¶
func TextVar(p encoding.TextUnmarshaler, name string, value encoding.TextMarshaler, usage string)
TextVar defines a env with a specified name, default value, and usage string. The argument p must be a pointer to a variable that will hold the value of the env, and p must implement encoding.TextUnmarshaler. If the env is used, the env value will be passed to p's UnmarshalText method. The type of the default value must be the same as the type of p.
Example ¶
package main import ( "fmt" "net" "os" "github.com/shaj13/env" ) func main() { fs := env.NewEnvSet("Example", env.ContinueOnError) fs.SetOutput(os.Stdout) var ip net.IP fs.TextVar(&ip, "IP", net.IPv4(192, 168, 0, 100), "`net.IP` to parse") // fs.Parse([]string{"EXAMPLE_IP=127.0.0.1"}) // fmt.Printf("{ip: %v}\n\n", ip) // 256 is not a valid IPv4 component ip = nil fs.Parse([]string{"EXAMPLE_IP=256.0.0.1"}) fmt.Printf("{ip: %v}\n\n", ip) }
Output: invalid value "256.0.0.1" for env IP: invalid IP address: 256.0.0.1 Usage of Example: EXAMPLE_IP net.IP net.IP to parse (default 192.168.0.100) {ip: <nil>}
func Uint ¶
Uint defines a uint env with specified name, default value, and usage string. The return value is the address of a uint variable that stores the value of the env.
func Uint64 ¶
Uint64 defines a uint64 env with specified name, default value, and usage string. The return value is the address of a uint64 variable that stores the value of the env.
func Uint64Var ¶
Uint64Var defines a uint64 env with specified name, default value, and usage string. The argument p points to a uint64 variable in which to store the value of the env.
func UintVar ¶
UintVar defines a uint env with specified name, default value, and usage string. The argument p points to a uint variable in which to store the value of the env.
func UnquoteUsage ¶
UnquoteUsage extracts a back-quoted name from the usage string for a env and returns it and the un-quoted usage. Given "a `name` to show" it returns ("name", "a name to show"). If there are no back quotes, the name is an educated guess of the type of the env's value.
func Var ¶
Var defines a env with the specified name and usage string. The type and value of the env are represented by the first argument, of type Value, which typically holds a user-defined implementation of Value. For instance, the caller could create a env that turns a comma-separated string into a slice of strings by giving the slice the methods of Value; in particular, Set would decompose the comma-separated string into the slice.
Types ¶
type Env ¶
type Env struct { Name string // name as it appears on environ Usage string // help message Value Value // value as set DefValue string // default value (as text); for usage message }
A Env represents the state of a environment variable.
type EnvSet ¶
type EnvSet struct { // Usage is the function called when an error occurs while parsing envs. // The field is a function (not a method) that may be changed to point to // a custom error handler. What happens after Usage is called depends // on the ErrorHandling setting; for the "Environ", this defaults // to ExitOnError, which exits the program after calling Usage. Usage func() // contains filtered or unexported fields }
A EnvSet represents a set of defined envs. The zero value of a EnvSet has no prefix and has ContinueOnError error handling.
Env names must be unique within a EnvSet. An attempt to define a env whose name is already in use will cause a panic.
Env names and prefix uppercased automatically i.e (foo => FOO).
func NewEnvSet ¶
func NewEnvSet(prefix string, errorHandling ErrorHandling) *EnvSet
NewEnvSet returns a new, empty env set with the specified prefix and error handling property. If the prefix is not empty, only env variables with the given prefix will be parsed, the prefix will be printed in the default usage message and in error messages.
func (*EnvSet) Bool ¶
Bool defines a bool env with specified name, default value, and usage string. The return value is the address of a bool variable that stores the value of the env.
func (*EnvSet) BoolVar ¶
BoolVar defines a bool env with specified name, default value, and usage string. The argument p points to a bool variable in which to store the value of the env.
func (*EnvSet) Duration ¶
Duration defines a time.Duration env with specified name, default value, and usage string. The return value is the address of a time.Duration variable that stores the value of the env. The env accepts a value acceptable to time.ParseDuration.
func (*EnvSet) DurationVar ¶
DurationVar defines a time.Duration env with specified name, default value, and usage string. The argument p points to a time.Duration variable in which to store the value of the env. The env accepts a value acceptable to time.ParseDuration.
func (*EnvSet) ErrorHandling ¶
func (e *EnvSet) ErrorHandling() ErrorHandling
ErrorHandling returns the error handling behavior of the env set.
func (*EnvSet) Float64 ¶
Float64 defines a float64 env with specified name, default value, and usage string. The return value is the address of a float64 variable that stores the value of the env.
func (*EnvSet) Float64Var ¶
Float64Var defines a float64 env with specified name, default value, and usage string. The argument p points to a float64 variable in which to store the value of the env.
func (*EnvSet) Func ¶
Func defines a env with the specified name and usage string. Each time the env is seen, fn is called with the value of the env. If fn returns a non-nil error, it will be treated as a env value parsing error.
func (*EnvSet) Init ¶
func (e *EnvSet) Init(prefix string, errorHandling ErrorHandling)
Init sets the prefix and error handling property for a env set. By default, the zero EnvSet uses an empty prefix and the ContinueOnError error handling policy.
func (*EnvSet) Int ¶
Int defines an int env with specified name, default value, and usage string. The return value is the address of an int variable that stores the value of the env.
func (*EnvSet) Int64 ¶
Int64 defines an int64 env with specified name, default value, and usage string. The return value is the address of an int64 variable that stores the value of the env.
func (*EnvSet) Int64Var ¶
Int64Var defines an int64 env with specified name, default value, and usage string. The argument p points to an int64 variable in which to store the value of the env.
func (*EnvSet) IntVar ¶
IntVar defines an int env with specified name, default value, and usage string. The argument p points to an int variable in which to store the value of the env.
func (*EnvSet) Lookup ¶
Lookup returns the Env structure of the named env, returning nil if none exists.
func (*EnvSet) Output ¶
Output returns the destination for usage and error messages. os.Stderr is returned if output was not set or was set to nil.
func (*EnvSet) Parse ¶
Parse parses env definitions from the envs list. Parse Must be called after all envs in the EnvSet are defined and before envs are accessed by the program.
func (*EnvSet) PrintDefaults ¶
func (e *EnvSet) PrintDefaults()
PrintDefaults prints, to standard error unless configured otherwise, the default values of all defined envs in the set. See the documentation for the global function PrintDefaults for more information.
func (*EnvSet) SetOutput ¶
SetOutput sets the destination for usage and error messages. If output is nil, os.Stderr is used.
func (*EnvSet) String ¶
String defines a string env with specified name, default value, and usage string. The return value is the address of a string variable that stores the value of the env.
func (*EnvSet) StringVar ¶
StringVar defines a string env with specified name, default value, and usage string. The argument p points to a string variable in which to store the value of the env.
func (*EnvSet) TextVar ¶
func (e *EnvSet) TextVar(p encoding.TextUnmarshaler, name string, value encoding.TextMarshaler, usage string)
TextVar defines a env with a specified name, default value, and usage string. The argument p must be a pointer to a variable that will hold the value of the env, and p must implement encoding.TextUnmarshaler. If the env is used, the env value will be passed to p's UnmarshalText method. The type of the default value must be the same as the type of p.
func (*EnvSet) Uint ¶
Uint defines a uint env with specified name, default value, and usage string. The return value is the address of a uint variable that stores the value of the env.
func (*EnvSet) Uint64 ¶
Uint64 defines a uint64 env with specified name, default value, and usage string. The return value is the address of a uint64 variable that stores the value of the env.
func (*EnvSet) Uint64Var ¶
Uint64Var defines a uint64 env with specified name, default value, and usage string. The argument p points to a uint64 variable in which to store the value of the env.
func (*EnvSet) UintVar ¶
UintVar defines a uint env with specified name, default value, and usage string. The argument p points to a uint variable in which to store the value of the env.
func (*EnvSet) Var ¶
Var defines a env with the specified name and usage string. The type and value of the env are represented by the first argument, of type Value, which typically holds a user-defined implementation of Value. For instance, the caller could create a env that turns a comma-separated string into a slice of strings by giving the slice the methods of Value; in particular, Set would decompose the comma-separated string into the slice.
type ErrorHandling ¶
type ErrorHandling int
ErrorHandling defines how EnvSet.Parse behaves if the parse fails.
const ( ContinueOnError ErrorHandling = iota // Return a descriptive error. ExitOnError // Call os.Exit(2). PanicOnError // Call panic with a descriptive error. )
These constants cause EnvSet.Parse to behave as described if the parse fails.
type Getter ¶
type Getter interface { Value Get() interface{} }
Getter is an interface that allows the contents of a Value to be retrieved. It wraps the Value interface, rather than being part of it, because it appeared after Go 1 and its compatibility rules. All Value types provided by this package satisfy the Getter interface, except the type used by Func.
type Value ¶
Value is the interface to the dynamic value stored in a env. (The default value is represented as a string.)
Set is called once, in environ order, for each env present. The env package may call the String method with a zero-valued receiver, such as a nil pointer.
Example ¶
package main import ( "fmt" "net/url" "github.com/shaj13/env" ) type URLValue struct { URL *url.URL } func (v URLValue) String() string { if v.URL != nil { return v.URL.String() } return "" } func (v URLValue) Set(s string) error { if u, err := url.Parse(s); err != nil { return err } else { *v.URL = *u } return nil } var u = &url.URL{} func main() { fs := env.NewEnvSet("Example", env.ExitOnError) fs.Var(&URLValue{u}, "URL", "URL to parse") fs.Parse([]string{"EXAMPLE_URL=https://pkg.go.dev/github.com/shaj13/env"}) fmt.Printf(`{scheme: %q, host: %q, path: %q}`, u.Scheme, u.Host, u.Path) }
Output: {scheme: "https", host: "pkg.go.dev", path: "/github.com/shaj13/env"}