env

package module
v0.0.4 Latest Latest
Warning

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

Go to latest
Published: Aug 8, 2025 License: MIT Imports: 5 Imported by: 7

README

Env

Minimalistic package for environment variable lookup of type defined in Parseable.

Example usage

package main

import (
	"github.com/smithy-security/pkg/env"
)

func main() {
	// Will error if not defined or a valid integer.
	intVar, err := env.GetOrDefault("MY_INT_ENV_VAR", 10)
	if err != nil {
		...
    }

	// Will return the default value 10 if not defined or on error
	anotherIntVar, err := env.GetOrDefault("MY_OTHER_INT_ENV_VAR", 10, env.WithDefaultOnError(true))
	if err != nil {
		...
	}
}

On testing

Customise Loader to mock your environment. Check the examples in env_test.go.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetOrDefault

func GetOrDefault[T Parseable](envVar string, defaultVal T, opts ...ParseOption) (dest T, err error)

GetOrDefault attempts to parse the environment variable provided. If it is empty or missing, the default value is used.

If an error is encountered, depending on whether the `WithDefaultOnError` option is provided it will either fall back or return the error back to the client.

Types

type Loader

type Loader func(key string) string

Loader is an alias for a function that loads values from the env. It mirrors the signature of os.Getenv.

type ParseOption

type ParseOption func(o *parseOpts) error

ParseOption is a means to customize parse options via variadic parameters.

func WithDefaultOnError

func WithDefaultOnError(fallback bool) ParseOption

WithDefaultOnError informs the parser that if an error is encountered during parsing, it should fallback to the default value.

func WithLoader

func WithLoader(loader Loader) ParseOption

WithLoader allows overriding how env vars are loaded.

Primarily used for testing.

type Parseable

type Parseable interface {
	string | bool | int | uint | uint32 | int64 | uint64 | float64 | time.Duration | time.Time
}

Parseable represents the types the parser is capable of handling. TODO: extend with slices if needed.

Jump to

Keyboard shortcuts

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