Documentation
¶
Index ¶
- Constants
- Variables
- func AreFalse(envs ...string) (ok bool)
- func AreTrue(envs ...string) (ok bool)
- func Bool(env string, fallback bool) bool
- func Duration(env string, fallback time.Duration) time.Duration
- func Exists(env string) (ok bool)
- func Float32(env string, fallback float32) float32
- func Float64(env string, fallback float64) float64
- func Int(env string, fallback int) int
- func Int64(env string, fallback int64) int64
- func Int64GreaterThan(env string, fallback, greaterThan int64) (ok bool)
- func Int64InRange(env string, fallback, min, max int64) (ok bool)
- func Int64LessThan(env string, fallback, lessThan int64) (ok bool)
- func IntGreaterThan(env string, fallback, greaterThan int) bool
- func IntInRange(env string, fallback, min, max int) bool
- func IntLessThan(env string, fallback, lessThan int) (ok bool)
- func IsFalse(env string) (ok bool)
- func IsTrue(env string) (ok bool)
- func List(env string, fallback []string) []string
- func ListContains(env string, fallback []string, contains string) (ok bool)
- func ListIsLength(env string, fallback []string, wantLength int) (ok bool)
- func ListLength(env string, fallback []string) int
- func Magic()
- func Map(env string, fallback map[string]string) map[string]string
- func MapHasKey(env string, fallback map[string]string, key string) (ok bool)
- func MapHasKeys(env string, fallback map[string]string, keys ...string) (ok bool)
- func MustExist(env string)
- func Set(env string, value string) error
- func String(env string, fallback string) string
- func UnitDuration(env string, fallback, unit time.Duration) time.Duration
- func Unset(env string) error
- func User() (u *user.User)
- func WasSet(env string, value string) bool
- func WasUnset(env string) bool
Constants ¶
const ( // LogFlags allows you to define the flags on log.New() for UseLogger's ErrLogger and OutLogger LogFlags int = log.Ldate | log.Ltime | log.Lshortfile // AmGoEnvMapSeparator allows you to define the default separator used for map items. Default is "," AmGoEnvMapSeparator string = "AM_GO_ENV_MAP_SEPARATOR" // AmGoEnvMapItemSeparator allows you to define how key and values in map items are split. Default is "=" AmGoEnvMapItemSeparator string = "AM_GO_ENV_MAP_ITEM_SEPARATOR" // AmGoEnvMapSplitN allows you to define the strings.SplitN n value. Default is "1" AmGoEnvMapSplitN string = "AM_GO_ENV_MAP_SPLIT_N" // AmGoEnvListSeparator allows you to define how list items are separated. Default is "," AmGoEnvListSeparator string = "AM_GO_ENV_LIST_SEPARATOR" // AmGoEnvUnitDurationBase allows you to define strconv.ParseInt base. Default is "10" AmGoEnvUnitDurationBase string = "AM_GO_ENV_UNIT_DURATION_BASE" // AmGoEnvUnitDurationBitSize allows you to define strconv.ParseInt bitSize. Default is "64" AmGoEnvUnitDurationBitSize string = "AM_GO_ENV_UNIT_DURATION_BIT_SIZE" // AmGoEnvDurationBase allows you to define strconv.ParseInt base. Default is "10" AmGoEnvDurationBase string = "AM_GO_ENV_DURATION_BASE" // AmGoEnvDurationBitSize allows you to define strconv.ParseInt bitSize. Default is "64" AmGoEnvDurationBitSize string = "AM_GO_ENV_DURATION_BIT_SIZE" // AmGoEnvFloat64BitSize allows you to define strconv.ParseFloat bitSize. Default is "64" AmGoEnvFloat64BitSize string = "AM_GO_ENV_FLOAT64_BIT_SIZE" // AmGoEnvFloat32BitSize allows you to define strconv.ParseFloat bitSize. Default is "32" AmGoEnvFloat32BitSize string = "AM_GO_ENV_FLOAT32_BIT_SIZE" // AmGoEnvInt64Base allows you to define strconv.ParseInt base. Default is "10" AmGoEnvInt64Base string = "AM_GO_ENV_INT64_BASE" // AmGoEnvInt64BitSize allows you to define strconv.ParseInt bitSize. Default is "64" AmGoEnvInt64BitSize string = "AM_GO_ENV_INT64_BIT_SIZE" // AmGoEnvAlwaysAllowPanic allows you to control whether panic() is permitted in MustExist AmGoEnvAlwaysAllowPanic string = "AM_GO_ENV_ALWAYS_ALLOW_PANIC" // AmGoEnvAlwaysPrintErrors allows you to control whether OutLogger and ErrLogger is leveraged AmGoEnvAlwaysPrintErrors string = "AM_GO_ENV_ALWAYS_PRINT_ERRORS" // AmGoEnvAlwaysUseLogger allows you to always use the OutLogger and ErrLogger AmGoEnvAlwaysUseLogger string = "AM_GO_ENV_ALWAYS_USE_LOGGER" // AmGoEnvEnableVerboseLogging allows you to enable verbose logging that writs to OutLogger AmGoEnvEnableVerboseLogging string = "AM_GO_ENV_ENABLE_VERBOSE_LOGGING" // AmGoEnvPanicNoUser allows you to panic() when user.Current() returns an error AmGoEnvPanicNoUser string = "AM_GO_ENV_PANIC_NO_USER" )
Variables ¶
var ( UseMagic bool = true // UseLogger controls whether or not the env package will use OutLogger or ErrLogger to report problems UseLogger bool // AllowPanic determines whether or not panic() should be called on MustExist AllowPanic bool // PanicNoUser determines on User() whether to throw a panic if the user.Current() returns an error PanicNoUser bool // PrintErrors determines whether or not PrintErrors bool // EnableVerboseLogging allows you to use the OutLogger to receive helpful debugging information EnableVerboseLogging bool // OutLogger defaults to STDOUT but requires UseLogger or AmGoEnvAlwaysUseLogger to be defined as 'true' OutLogger *log.Logger // ErrLogger defaults to STDERR but requires UseLogger or AmGoEnvAlwaysUseLogger to be defined as 'true' ErrLogger *log.Logger // ShowVerbose is enabled when UseLogger and EnableVerboseLogging are enabled ShowVerbose bool )
RUNTIME CONTROL
var ( // ListSeparator defines how a list is split, CSV uses "," and TSV uses "|", you can customize this to anything ListSeparator string = "," // MapSeparator defines how key=value pairs in a map are split, csv uses ",", tsv uses "|" inside Map MapSeparator string = "," // MapItemSeparator defines how keys and values are split in the string inside Map MapItemSeparator string = "=" // MapSplitN defines the default behavior on strings.SplitN inside Map MapSplitN int = 2 // Float64BitSize allows you to define the default behavior of the strconv.ParseFloat inside Float64 Float64BitSize int = 64 // Float32BitSize allows you to define the default behavior of the strconv.ParseFloat inside Float32 Float32BitSize int = 32 // DurationBase allows you to define the default behavior of the strconv.ParseInt inside Duration DurationBase int = 10 // DurationBitSize allows you to define the default behavior of the strconv.ParseInt inside Duration DurationBitSize int = 64 // UnitDurationBase allows you to define the default behavior of the strconv.ParseInt inside UnitDuration UnitDurationBase int = 10 // UnitDurationBitSize allows you to define the default behavior of the strconv.ParseInt inside UnitDuration UnitDurationBitSize int = 64 // Int64Base allows you to define the default behavior of strconv.ParseInt inside Int64 Int64Base int = 10 // Int64BitSize allows you to define the default behavior of strconv.ParseInt inside Int64 Int64BitSize int = 64 )
Functions ¶
func AreFalse ¶
AreFalse returns true only if all specified environment variables are false or unset.
Example:
if env.AreFalse("DISABLED", "LEGACY_MODE") {
// ...
}
func AreTrue ¶
AreTrue returns true only if all specified environment variables are true.
Example:
if env.AreTrue("ENABLED", "FEATURE_X_ON") {
// ...
}
func Bool ¶
Bool parses an environment variable as a boolean. It accepts "true", "t", "1" as true and "false", "f", "0" as false. If the variable is unset or fails to parse, it returns the fallback value.
Example:
useJson := env.Bool("USE_JSON", false)
func Duration ¶
Duration parses an environment variable as a time.Duration. It can parse duration strings like "300ms", "1.5h" or an integer number of nanoseconds.
Example:
timeout := env.Duration("TIMEOUT", 5*time.Second)
func Exists ¶
Exists checks if an environment variable is set.
Example:
ok := env.Exists("HOSTNAME")
func Float32 ¶
Float32 gets a float32 value from an environment variable, or a fallback if not set or invalid.
Example:
pi := env.Float32("PI", float32(3.14))
func Float64 ¶
Float64 gets a float64 value from an environment variable, or a fallback if not set or invalid.
Example:
pi := env.Float64("PI", float64(3.14))
func Int ¶
Int gets an integer value from an environment variable, or a fallback if not set or invalid.
Example:
port := env.Int("PORT", 3306)
func Int64 ¶
Int64 gets an int64 value from an environment variable, or a fallback if not set or invalid.
Example:
ns := env.Int64("NANOSECONDS", int64(1_000_000_000))
func Int64GreaterThan ¶
Int64GreaterThan checks if an int64 from an env var is greater than a given value.
Example:
if env.Int64GreaterThan("HITS", 0, 1000) {
log.Fatal("Maximum hits received.")
}
func Int64InRange ¶
Int64InRange checks if an int64 from an env var is within a given range (inclusive).
Example:
if env.Int64InRange("YEAR", 2020, 2000, 2025) {
fmt.Println("Valid year!")
}
func Int64LessThan ¶
Int64LessThan checks if an int64 from an env var is less than a given value.
Example:
if env.Int64LessThan("HITS", 0, 100) {
fmt.Println("Still under threshold.")
}
func IntGreaterThan ¶
IntGreaterThan checks if an int from an env var is greater than a given value.
Example:
if env.IntGreaterThan("CONNECTIONS", 0, 100) {
log.Fatal("Connection limit exceeded.")
}
func IntInRange ¶
IntInRange checks if an int from an env var is within a given range (inclusive).
Example:
if env.IntInRange("PORT", 8080, 1024, 49151) {
fmt.Println("Port is in the user range.")
}
func IntLessThan ¶
IntLessThan checks if an int from an env var is less than a given value.
Example:
if env.IntLessThan("RETRIES", 0, 3) {
fmt.Println("Still have retries left.")
}
func IsFalse ¶
IsFalse returns true if an environment variable is "false" or is not set.
Example:
if env.IsFalse("USE_JSON") {
fmt.Println("Not using JSON.")
}
func IsTrue ¶
IsTrue returns true only if an environment variable is explicitly "true".
Example:
if env.IsTrue("USE_JSON") {
// intend to use json
}
func List ¶
List parses a delimited string from an environment variable into a []string. The delimiter is configured by the global `ListSeparator` variable.
Example:
# With ENV TAGS="go,docker,linux"
tags := env.List("TAGS", []string{})
func ListContains ¶
ListContains checks if a list parsed from an env var contains a specific string (case-insensitive).
Example:
if env.ListContains("FEATURES", env.ZeroList, "beta") {
// ...
}
func ListIsLength ¶
ListIsLength checks if a list parsed from an env var has a specific length.
Example:
if !env.ListIsLength("HOSTS", env.ZeroList, 3) {
panic("env HOSTS must have exactly 3 items")
}
func ListLength ¶
ListLength returns the number of elements in a list parsed from an env var.
Example:
if env.ListLength("HOSTS", env.ZeroList) > 3 {
fmt.Println("Warning: too many hosts specified.")
}
func Magic ¶
func Magic()
Magic will read the environment of the runtime where this package is imported and will attempt to reassign the variables used throughout the application like UseLogger, AllowPanic, etc. where these values are retrieved using their related Bool(), Int(), String() functions accordingly. Naming pattern of these are AM_GO_ENV_<UPPER_UNDERLINE_CONVERSION> so UseLogger would be AM_GO_ENV_USE_LOGGER
func Map ¶
Map parses a delimited string from an env var into a map[string]string. Delimiters are configured by `MapSeparator` and `MapItemSeparator`.
Example:
# With ENV DATA="key1=val1,key2=val2"
data := env.Map("DATA", env.ZeroMap)
func MapHasKey ¶
MapHasKey checks if a map parsed from an env var contains a specific key.
Example:
if !env.MapHasKey("CONFIG", env.ZeroMap, "domain") {
panic("missing required key 'domain' from CONFIG env value")
}
func MapHasKeys ¶
MapHasKeys checks if a map parsed from an env var contains all specified keys.
Example:
required := []string{"env", "author", "customer"}
if env.MapHasKeys("TAGS", env.ZeroMap, required...) {
fmt.Println("TAGS contain required keys!")
}
func MustExist ¶
func MustExist(env string)
MustExist panics or exits if an environment variable is not set. The behavior is controlled by the AllowPanic and PrintErrors global variables.
Example:
func init() {
env.MustExist("REQUIRED_VAR")
}
func Set ¶
Set wraps os.Setenv, returning an error if it fails.
Example:
err := env.Set("BACKUPS_DIR", "/tmp/backups")
if err != nil {
log.Fatal(err)
}
func String ¶
String gets a string value from an environment variable, or a fallback if not set.
Example:
hostname := env.String("HOSTNAME", "localhost")
func UnitDuration ¶
UnitDuration parses an environment variable as a number and multiplies it by the given unit. It can also parse full duration strings like "1h30m", in which case the unit is ignored. NOTE: The value of the env **AND** the fallback will be multiplied by the unit variable.
Example:
# TIMEOUT=10 will result in 10 * time.Second
timeout := env.UnitDuration("TIMEOUT", 5, time.Second)
func Unset ¶
Unset wraps os.Unsetenv, returning an error if it fails.
Example:
err := env.Unset("OLD_VAR")
func User ¶
User returns the current user. If an error occurs, it may panic or return a default user, depending on global configuration (PanicNoUser).
Example:
fmt.Printf("Your Home Directory: %s", env.User().HomeDir)
Types ¶
This section is empty.