getenv

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jan 7, 2026 License: MIT Imports: 7 Imported by: 4

README

Version Go Test go code golangci-lint Documentation Go Report Card codecov Powered by Rake

getenv

A minimalist Go library for type-safe environment variable parsing, inspired by the standard flag package.

This library allows you to effortlessly use environment variables within your code. It reads the values of environment variables using built-in types, assigns fallback (default) values if no value is set, and performs type-based validation to ensure correctness.

The currently supported built-in types are:

getenv.Bool
getenv.Int
getenv.Int64
getenv.Float64
getenv.String
getenv.Duration
getenv.TCPAddr
getenv.StringSlice
getenv.LogLevel

Installation

go get -u github.com/vigo/getenv

Usage

For getenv.Bool:

color := getenv.Bool("COLOR", false)  // COLOR doesn’t exist in the environment
if err := getenv.Parse(); err != nil {
	log.Fatal(err)
}

fmt.Println(*color) // false as bool

For getenv.Int:

port := getenv.Int("PORT", 8000) // PORT doesn’t exist in the environment
if err := getenv.Parse(); err != nil {
	log.Fatal(err)
}

fmt.Println(*port) // 8000 as int

For getenv.Int64:

long := getenv.Int64("LONG", 9223372036854775806) // LONG doesn’t exist in the environment
if err := getenv.Parse(); err != nil {
	log.Fatal(err)
}

fmt.Println(*long) // 9223372036854775806 as int64

For getenv.Float64:

xFactor := getenv.Float64("X_FACTOR", 1.1) // X_FACTOR doesn’t exist in the environment
if err := getenv.Parse(); err != nil {
	log.Fatal(err)
}

fmt.Println(*xFactor) // 1.1 as float64

For getenv.String:

hmacHeader := getenv.String("HMAC_HEADER", "X-Foo-Signature") // HMAC_HEADER doesn’t exist in the environment
if err := getenv.Parse(); err != nil {
	log.Fatal(err)
}

fmt.Println(*hmacHeader) // X-Foo-Signature as string

For getenv.Duration:

timeout := getenv.Duration("SERVER_TIMEOUT", 5*time.Second) // SERVER_TIMEOUT doesn’t exist in the environment
if err := getenv.Parse(); err != nil {
	log.Fatal(err)
}

fmt.Println(*timeout) // 5s as time.Duration

For getenv.TCPAddr:

listen := getenv.TCPAddr("LISTEN", ":4000") // LISTEN doesn't exist in the environment
if err := getenv.Parse(); err != nil {
	log.Fatal(err)
}

fmt.Println(*listen) // :4000 as string

For getenv.StringSlice:

// BROKERS doesn't exist in the environment
brokers := getenv.StringSlice("BROKERS", []string{":9092", ":9093"})
if err := getenv.Parse(); err != nil {
	log.Fatal(err)
}

fmt.Println(*brokers) // [:9092 :9093] as []string

// if BROKERS=":9092,:9093,127.0.0.1:9094" exists in the environment
// result will be: [:9092 :9093 127.0.0.1:9094]
// - values are split by comma
// - whitespace is trimmed
// - empty values are filtered out

For getenv.LogLevel:

// define your custom log levels
levels := map[string]int{
	"DEBUG": 0,
	"INFO":  1,
	"WARN":  2,
	"ERROR": 3,
	"FATAL": 4,
}

// LOG_LEVEL doesn't exist in the environment, default is INFO (1)
logLevel := getenv.LogLevel("LOG_LEVEL", levels, 1)
if err := getenv.Parse(); err != nil {
	log.Fatal(err)
}

fmt.Println(*logLevel) // 1 as int

// if LOG_LEVEL=debug exists in the environment (case-insensitive)
// result will be: 0

For all of them together:

color := getenv.Bool("COLOR", false)
port := getenv.Int("PORT", 8000)
long := getenv.Int64("LONG", 9223372036854775806)
xFactor := getenv.Float64("X_FACTOR", 1.1)
hmacHeader := getenv.String("HMAC_HEADER", "X-Foo-Signature")
timeout := getenv.Duration("SERVER_TIMEOUT", 5*time.Second)
listen := getenv.TCPAddr("LISTEN", ":4000")
brokers := getenv.StringSlice("BROKERS", []string{":9092", ":9093"})

levels := map[string]int{"DEBUG": 0, "INFO": 1, "WARN": 2, "ERROR": 3}
logLevel := getenv.LogLevel("LOG_LEVEL", levels, 1)

if err := getenv.Parse(); err != nil {
	log.Fatal(err)
}

// now you have all the variables accessible via pointer...

Package also provides error types:

getenv.ErrInvalid
getenv.ErrEnvironmentVariableIsEmpty

Use with:

  • errors.Is(err, getenv.ErrInvalid)
  • errors.Is(err, getenv.ErrEnvironmentVariableIsEmpty)

Feel free to contribute!


Rake Tasks

rake -T

rake coverage  # show test coverage
rake test      # run test

License

This project is licensed under MIT (MIT)


This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the code of conduct.

Documentation

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	ErrEnvironmentVariableNotFound = errors.New("not found")
	ErrEnvironmentVariableIsEmpty  = errors.New("is empty")
	ErrInvalid                     = errors.New("invalid")
)

sentinel errors.

Functions

func Bool

func Bool(name string, value bool) *bool

Bool sets environment variable and returns the pointer of value.

Example
package main

import (
	"fmt"

	"github.com/vigo/getenv"
)

func main() {
	color := getenv.Bool("COLOR", false)
	if err := getenv.Parse(); err != nil {
		fmt.Println(err)
		return
	}

	fmt.Println(*color)
}
Output:

false

func Duration

func Duration(name string, value time.Duration) *time.Duration

Duration sets environment variable and returns the pointer of value.

Example
package main

import (
	"fmt"
	"time"

	"github.com/vigo/getenv"
)

func main() {
	timeout := getenv.Duration("SERVER_TIMEOUT", 5*time.Second)
	if err := getenv.Parse(); err != nil {
		fmt.Println(err)
		return
	}

	fmt.Println(*timeout)
}
Output:

5s

func Float64

func Float64(name string, value float64) *float64

Float64 sets environment variable and returns the pointer of value.

Example
package main

import (
	"fmt"

	"github.com/vigo/getenv"
)

func main() {
	xFactor := getenv.Float64("X_FACTOR", 1.1)
	if err := getenv.Parse(); err != nil {
		fmt.Println(err)
		return
	}

	fmt.Println(*xFactor)
}
Output:

1.1

func Int

func Int(name string, value int) *int

Int sets environment variable and returns the pointer of value.

Example
package main

import (
	"fmt"

	"github.com/vigo/getenv"
)

func main() {
	port := getenv.Int("PORT", 8000)
	if err := getenv.Parse(); err != nil {
		fmt.Println(err)
		return
	}

	fmt.Println(*port)
}
Output:

8000

func Int64

func Int64(name string, value int64) *int64

Int64 sets environment variable and returns the pointer of value.

Example
package main

import (
	"fmt"

	"github.com/vigo/getenv"
)

func main() {
	long := getenv.Int64("LONG", 9223372036854775806)
	if err := getenv.Parse(); err != nil {
		fmt.Println(err)
		return
	}

	fmt.Println(*long)
}
Output:

9223372036854775806

func LogLevel added in v0.1.0

func LogLevel(name string, levels map[string]int, defaultValue int) *int

LogLevel sets environment variable and returns the pointer of value.

Example
package main

import (
	"fmt"

	"github.com/vigo/getenv"
)

func main() {
	levels := map[string]int{
		"DEBUG": 0,
		"INFO":  1,
		"WARN":  2,
		"ERROR": 3,
	}
	logLevel := getenv.LogLevel("LOG_LEVEL", levels, 1)
	if err := getenv.Parse(); err != nil {
		fmt.Println(err)
		return
	}

	fmt.Println(*logLevel)
}
Output:

1

func Parse

func Parse() error

Parse handles environment variable set/assign operations.

func Reset

func Reset()

Reset resets/clears variables storage.

func String

func String(name string, value string) *string

String sets environment variable and returns the pointer of value.

Example
package main

import (
	"fmt"

	"github.com/vigo/getenv"
)

func main() {
	hmacHeader := getenv.String("HMAC_HEADER", "X-Foo-Signature")
	if err := getenv.Parse(); err != nil {
		fmt.Println(err)
		return
	}

	fmt.Println(*hmacHeader)
}
Output:

X-Foo-Signature

func StringSlice added in v0.1.0

func StringSlice(name string, value []string) *[]string

StringSlice sets environment variable and returns the pointer of value.

Example
package main

import (
	"fmt"

	"github.com/vigo/getenv"
)

func main() {
	brokers := getenv.StringSlice("BROKERS", []string{":9092", ":9093"})
	if err := getenv.Parse(); err != nil {
		fmt.Println(err)
		return
	}

	fmt.Println(*brokers)
}
Output:

[:9092 :9093]

func TCPAddr

func TCPAddr(name string, value string) *string

TCPAddr sets environment variable and returns the pointer of value.

Example
package main

import (
	"fmt"

	"github.com/vigo/getenv"
)

func main() {
	listen := getenv.TCPAddr("LISTEN", ":4000")
	if err := getenv.Parse(); err != nil {
		fmt.Println(err)
		return
	}

	fmt.Println(*listen)
}
Output:

:4000

func ValidateTCPNetworkAddress

func ValidateTCPNetworkAddress(addr string) (*net.TCPAddr, error)

ValidateTCPNetworkAddress validates given tcp address as string and returns an error if the provided arg is not a valid tcp address.

Types

type EnvironmentVariable

type EnvironmentVariable struct {
	Value Value
	Name  string
}

EnvironmentVariable represents environment variable.

type EnvironmentVariableSet

type EnvironmentVariableSet struct {
	// contains filtered or unexported fields
}

EnvironmentVariableSet mimics flag.FlagSet type.

func (*EnvironmentVariableSet) Bool

func (e *EnvironmentVariableSet) Bool(name string, value bool) *bool

Bool creates new bool.

func (*EnvironmentVariableSet) BoolVar

func (e *EnvironmentVariableSet) BoolVar(p *bool, name string, value bool)

BoolVar creates new bool variable.

func (*EnvironmentVariableSet) Duration

func (e *EnvironmentVariableSet) Duration(name string, value time.Duration) *time.Duration

Duration creates new duration.

func (*EnvironmentVariableSet) DurationVar

func (e *EnvironmentVariableSet) DurationVar(p *time.Duration, name string, value time.Duration)

DurationVar creates new duration variable.

func (*EnvironmentVariableSet) Float64

func (e *EnvironmentVariableSet) Float64(name string, value float64) *float64

Float64 creates new float64.

func (*EnvironmentVariableSet) Float64Var

func (e *EnvironmentVariableSet) Float64Var(p *float64, name string, value float64)

Float64Var creates new float64 variable.

func (*EnvironmentVariableSet) Int

func (e *EnvironmentVariableSet) Int(name string, value int) *int

Int creates new int.

func (*EnvironmentVariableSet) Int64

func (e *EnvironmentVariableSet) Int64(name string, value int64) *int64

Int64 creates new int64.

func (*EnvironmentVariableSet) Int64Var

func (e *EnvironmentVariableSet) Int64Var(p *int64, name string, value int64)

Int64Var creates new int64 variable.

func (*EnvironmentVariableSet) IntVar

func (e *EnvironmentVariableSet) IntVar(p *int, name string, value int)

IntVar creates new int variable.

func (*EnvironmentVariableSet) LogLevel added in v0.1.0

func (e *EnvironmentVariableSet) LogLevel(name string, levels map[string]int, value int) *int

LogLevel creates new log level.

func (*EnvironmentVariableSet) LogLevelVar added in v0.1.0

func (e *EnvironmentVariableSet) LogLevelVar(p *int, name string, levels map[string]int, value int)

LogLevelVar creates new log level variable.

func (*EnvironmentVariableSet) Parse

func (e *EnvironmentVariableSet) Parse() error

Parse fetches environment variable, creates required Value, sets and stores.

func (*EnvironmentVariableSet) Reset

func (e *EnvironmentVariableSet) Reset()

Reset resets variables storage.

func (*EnvironmentVariableSet) String

func (e *EnvironmentVariableSet) String(name string, value string) *string

String creates new string.

func (*EnvironmentVariableSet) StringSlice added in v0.1.0

func (e *EnvironmentVariableSet) StringSlice(name string, value []string) *[]string

StringSlice creates new string slice.

func (*EnvironmentVariableSet) StringSliceVar added in v0.1.0

func (e *EnvironmentVariableSet) StringSliceVar(p *[]string, name string, value []string)

StringSliceVar creates new string slice variable.

func (*EnvironmentVariableSet) StringVar

func (e *EnvironmentVariableSet) StringVar(p *string, name string, value string)

StringVar creates new string variable.

func (*EnvironmentVariableSet) TCPAddr

func (e *EnvironmentVariableSet) TCPAddr(name string, value string) *string

TCPAddr creates new tcp addr.

func (*EnvironmentVariableSet) TCPAddrVar

func (e *EnvironmentVariableSet) TCPAddrVar(p *string, name string, value string)

TCPAddrVar creates new string variable for tcp address value.

func (*EnvironmentVariableSet) Var

func (e *EnvironmentVariableSet) Var(value Value, name string)

Var stores EnvironmentVariable type.

type Value

type Value interface {
	Set(s string) error
	Get() any
}

Value defines environment variable's value behaviours.

Jump to

Keyboard shortcuts

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