env

package
v0.0.0-...-11bf18d Latest Latest
Warning

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

Go to latest
Published: Aug 11, 2025 License: Apache-2.0 Imports: 8 Imported by: 2

README

ENV

This go package is designed to give you easy access to interact with the ENV to request types back when working with Linux operating systems (including macOS Silicon and Intel).

Installation

go get -u github.com/andreimerlescu/env

Package Usage

package main

import (
    "fmt"
    "strings"
    "time"
    
    "github.com/andreimerlescu/env"
)

func main() {
    hostname := env.String("HOSTNAME", "localhost")
    port := env.Int("PORT", 3306)
    user := env.String("USERNAME", "user")
    pass := env.String("PASSWORD", "")
    timeout := env.UnitDuration("TIMEOUT", time.Duration(3), time.Second)
    pi := env.Float64("PI", 3.14)
    pii := env.Float32("PI", 3.33)
    tags := env.List("TAGS", env.ZeroList)
    properties := env.Map("TAGS", env.ZeroMap)
    
    fmt.Println(
        hostname, 
        port, 
        user, 
        strings.Repeat("*", len(pass)), 
        pi, 
        pii, 
        timeout, 
        strings.Join(tags, ","), 
        properties)
}

Function List

  • Can panic() with export AM_GO_ENV_ALWAYS_ALLOW_PANIC=true
    • func User() (u *user.User)
    • func MustExist(env string)
  • Types
    • func Bool(env string, fallback bool) bool
    • func String(env string, fallback string) string
    • func Int(env string, fallback int) int
    • func Int64(env string, fallback int64) int64
    • func Float32(env string, fallback float32) float32
    • func Float64(env string, fallback float64) float64
    • func Duration(env string, fallback time.Duration) time.Duration
    • func UnitDuration(env string, fallback, unit time.Duration) time.Duration
    • func List(env string, fallback []string) []string
    • func Map(env string, fallback map[string]string) map[string]string
  • Data Control
    • func Unset(env string)
    • func ListLength(env string, fallback []string) int
    • func Set(env string, value string)
  • Conditionals
    • func Exists(env string) (ok bool)
    • func IsFalse(env string) (ok bool)
    • func IsTrue(env string) (ok bool)
    • func AreTrue(envs ...string) (ok bool)
    • func AreFalse(envs ...string) (ok bool)
    • func WasSetWasSet(env string, value string) (ok bool)
    • func WasUnset(env string) (ok bool)
    • func Int64LessThan(env string, fallback, lessThan int64) (ok bool)
    • func Int64GreaterThan(env string, fallback, greaterThan int64) (ok bool)
    • func Int64InRange(env string, fallback, min, max int64) (ok bool)
    • func IntLessThan(env string, fallback, lessThan int) (ok bool)
    • func IntGreaterThan(env string, fallback, greaterThan int) (ok bool)
    • func IntInRange(env string, fallback, min, max int) (ok bool)
    • func ListContains(env string, fallback []string, contains string) (ok bool)
    • func ListIsLength(env string, fallback []string, wantLength int) (ok bool)
    • func MapHasKeys(env string, fallback map[string]string, keys ...string) (ok bool)
    • func MapHasKey(env string, fallback map[string]string, key string) (ok bool)

Package Control Variables

This package can be manipulated using some control variables in your runtime when you're consuming the package. For instance, you can define what makes a list from a string, ie. how you split the string. The property ListSeparator defaults to , but allows you to change it. Additionally, there is MapSeparator (default ,) and MapItemSeparator (default =) that allows you to define how a string can become a map[string]string via key1=value,key2=value via , & =, but you can change it to anything.

package main

import (
	"fmt"
    
    "github.com/andreimerlescu/env"
)

func main(){
    // Lists
    env.Set("TEST_LIST", "item1|item2|item3")
    env.ListSeparator = "|" 
    items := env.List("TEST_LIST", env.ZeroList)
    for i, item := range items {
		fmt.Printf("TEST_LIST#%d=%s\n", i, item)
    }
    
    // Maps
    env.Set("TEST_MAP", "key1~value|key2~value")
    env.MapSeparator = "|" 
    env.MapItemSeparator = "~"
	env.MapSplitN = 2 // default
    properties := env.Map("TEST_MAP", env.ZeroMap)
    for key, value := range properties {
        fmt.Printf("TEST_MAP[%s]=%s\n", key, value)
    }
}

Additionally, you can modify the default behavior in the way strconv.ParseInt and strconv.ParseFloat customize the base and bitSize argument values when used in conjunction with env.

Variable Type Default Usage
Int64Base int 10 The base value of the number.
Int64BitSize int 64 The bitSize value of the number.
Float32BitSize int 32 The bitSize value of the number.
Float64BitSize int 64 The bitSize of the value of the number.
DurationBase int 10 The base value of number.
DurationBitSize int 10 The bitSize value of the number.
UnitDurationBase int 10 The base value of the number.
UnitDurationBitSize int 64 The bitSize value of the number.

Types

String
env.String("<ENV>", "<DEFAULT>")
Int
env.Int("<ENV>", <DEFAULT>)
Int64
env.Int64("<ENV>", <DEFAULT>)
Float32
env.Float32("<ENV>", <DEFAULT>)
Float64
env.Float64("<ENV>", <DEFAULT>)
Duration
env.Duration("<ENV>", <DEFAULT>)
UnitDuration
env.UnitDuration("<ENV>", <DEFAULT>, time.<UNIT>)
Map
env.Map("<ENV>", map[string]string{"<KEY>": "<VALUE>"})

Environment Controls

You can use the following environment variables to define defaults used by the package across the runtime of any go binary that uses this package. Useful if you're enforcing base 8 math on in64 operations.

Environment Variable Type Default Usage
AM_GO_ENV_MAP_SEPARATOR String , How map items are separated.
AM_GO_ENV_MAP_ITEM_SEPARATOR String = How keys and values in map items are separated.
AM_GO_ENV_MAP_SPLIT_N Int 1 How many AM_GO_ENV_MAP_ITEM_SEPARATOR to strings.SplitN on.
AM_GO_ENV_LIST_SEPARATOR String , How list items are separated.
AM_GO_ENV_UNIT_DURATION_BASE Int 10 How strconv.ParseInt defines base by default.
AM_GO_ENV_UNIT_DURATION_BIT_SIZE Int 64 How strconv.ParseInt defines bitSize by default.
AM_GO_ENV_DURATION_BASE Int 10 How strconv.ParseInt defines base by default.
AM_GO_ENV_DURATION_BIT_SIZE Int 64 How strconv.ParseInt defines bitSize by default.
AM_GO_ENV_FLOAT64_BIT_SIZE Int 64 How strconv.ParseFloat defines bitSize by default.
AM_GO_ENV_FLOAT32_BIT_SIZE Int 32 How strconv.ParseFloat defines bitSize by default.
AM_GO_ENV_INT64_BASE Int 10 How strconv.ParseInt defines base by default.
AM_GO_ENV_INT64_BIT_SIZE Int 64 How strconv.ParseInt defines bitSize by default.
AM_GO_ENV_ALWAYS_ALLOW_PANIC Bool false Permit the use of panic() within the package.
AM_GO_ENV_ALWAYS_PRINT_ERRORS Bool false Permit writing to STDERR to be returned.
AM_GO_ENV_ALWAYS_USE_LOGGER Bool false Permit the STDOUT, STDERR logger to be used.
AM_GO_ENV_ENABLE_VERBOSE_LOGGING Bool false Permit the STDOUT logger to report when something wasn't fully successful.
AM_GO_ENV_PANIC_NO_USER Bool false Use panic() over os.Exit(1) when user.Current() returns an error.

License

This package is Open Source and is licensed with the Apache 2.0 License.

Why?

I really like clean code, and I find that when working with the environment in an application, it can get messy. This package is my solution that. I wanted a way to quickly interact with the os.Environ() without having to do so much repetitive work across each project. Thus, why this package was born. I just merged that work and forked it into its own package so it can be used externally and enhanced to a better purpose.

This package is called env and it is NOT made for Windows, but if you're on Windows, feel free to try it out. Enjoy using it!

Documentation

Index

Constants

View Source
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

View Source
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

View Source
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
)
View Source
var (
	ZeroInt          int           = 0
	ZeroInt64        int64         = 0
	ZeroFloat64      float64       = 0
	ZeroFloat32      float32       = 0
	ZeroBool         bool          = false
	ZeroString       string        = ""
	ZeroDuration     time.Duration = 0
	ZeroUnitDuration time.Duration = 0
	ZeroList         []string
	ZeroMap          map[string]string
)

Functions

func AreFalse

func AreFalse(envs ...string) (ok bool)

AreFalse returns true only if all specified environment variables are false or unset.

Example:

if env.AreFalse("DISABLED", "LEGACY_MODE") {
   // ...
}

func AreTrue

func AreTrue(envs ...string) (ok bool)

AreTrue returns true only if all specified environment variables are true.

Example:

if env.AreTrue("ENABLED", "FEATURE_X_ON") {
   // ...
}

func Bool

func Bool(env string, fallback bool) 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

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

func Exists(env string) (ok bool)

Exists checks if an environment variable is set.

Example:

ok := env.Exists("HOSTNAME")

func Float32

func Float32(env string, fallback float32) 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

func Float64(env string, fallback float64) 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

func Int(env string, fallback int) 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

func Int64(env string, fallback int64) 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

func Int64GreaterThan(env string, fallback, greaterThan int64) (ok bool)

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

func Int64InRange(env string, fallback, min, max int64) (ok bool)

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

func Int64LessThan(env string, fallback, lessThan int64) (ok bool)

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

func IntGreaterThan(env string, fallback, greaterThan int) bool

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

func IntInRange(env string, fallback, min, max int) bool

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

func IntLessThan(env string, fallback, lessThan int) (ok bool)

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

func IsFalse(env string) (ok bool)

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

func IsTrue(env string) (ok bool)

IsTrue returns true only if an environment variable is explicitly "true".

Example:

if env.IsTrue("USE_JSON") {
   // intend to use json
}

func List

func List(env string, fallback []string) []string

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

func ListContains(env string, fallback []string, contains string) (ok bool)

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

func ListIsLength(env string, fallback []string, wantLength int) (ok bool)

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

func ListLength(env string, fallback []string) int

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

func Map(env string, fallback map[string]string) map[string]string

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

func MapHasKey(env string, fallback map[string]string, key string) (ok bool)

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

func MapHasKeys(env string, fallback map[string]string, keys ...string) (ok bool)

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

func Set(env string, value string) error

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

func String(env string, fallback string) string

String gets a string value from an environment variable, or a fallback if not set.

Example:

hostname := env.String("HOSTNAME", "localhost")

func UnitDuration

func UnitDuration(env string, fallback, unit time.Duration) time.Duration

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

func Unset(env string) error

Unset wraps os.Unsetenv, returning an error if it fails.

Example:

err := env.Unset("OLD_VAR")

func User

func User() (u *user.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)

func WasSet

func WasSet(env string, value string) bool

WasSet allows you to conditionally check if an ENV was defined for the runtime

Example:

u, _ := user.
if !env.WasSet("BACKUPS_DIR", filepath.Join(env.User().HomeDir, "backups")) {
	// failed to set ENV "BACKUPS_DIR"
}

func WasUnset

func WasUnset(env string) bool

WasUnset allows you to conditionally check if an ENV was unset for the runtime

Example:

u, _ := user.
if !env.WasUnset("BACKUPS_DIR") {
	// failed to unset ENV "BACKUPS_DIR"
}

Types

This section is empty.

Jump to

Keyboard shortcuts

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