envparser

package module
v1.0.5 Latest Latest
Warning

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

Go to latest
Published: Apr 28, 2025 License: MIT Imports: 7 Imported by: 1

README

envparser

Lint, test, and build

Declare your application environment variables in a standardised way!

Purpose and usage

Tired of inconsistent environment variable handling 😮‍💨? Tired of having to use os.LookupEnv and implementing parsing every time you need to extract a value 😩? Are you especially tired of seeing duplicate code blocks when variables are used in more than one place 😤? I was one of you... Enter standardized environment variable parsing!

A stepwise instruction for a better way of life:

  1. Define a place where you want your environment variables to be declared. This could be your application's main entrypoint, or a separate env package, whatever your heart desires.
  2. Register your environment variables in the chosen place. Determine which are required and their datatypes.
  3. Call Parse() and your declared variables are good to go.
package main

import (
  env "github.com/trebent/envparser"
  logging "github.com/trebent/megaapp/log"
)

var (
  logLevel = env.Register(*env.Opts[string]{
    Name:     "LOG_LEVEL",
    Desc:     "The log level of the application.",
    Required: true,
  })
)

func main() {
  // Output the environment parser help text to stdout when --help is executed.
  flag.CommandLine.SetOutput(os.Stdout)
	flag.Usage = func() {
		fmt.Fprintf(flag.CommandLine.Output(), "Usage of %s:\n", os.Args[0])
		fmt.Fprintf(flag.CommandLine.Output(), "\n")
		fmt.Fprintf(flag.CommandLine.Output(), envparser.Help())
	}
	flag.Parse()

  // Exits with exit code 1 in case the registered environment variables could
  // not be parsed according to the rules you set up.
  _ = env.Parse()

  logging.SetLogLevel(logLevel.Value())
  ...
}

Documentation

See the Golang package. Documentation is provided as part of the code.

Documentation

Overview

Package envparser is a simple no-dependency library for parsing environment variables in Go.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrName              = errors.New("variable name is invalid")
	ErrNameExists        = errors.New("variable name already exists")
	ErrRequired          = errors.New("variable is required")
	ErrCreateAndRequired = errors.New(
		"variable can't be marked for creation and required at the same time",
	)
	ErrValidate = errors.New("variable validation failed")
	ErrAccepted = errors.New("variable value not in accepted values")

	// ExitOnError ensures that encountered errors are printed to stderr and the
	// program exits with code 1. If not set, errors are returned to the caller.
	//nolint:gochecknoglobals
	ExitOnError = true

	// Prefix is the prefix used for environment variables. If set, all
	// environment variables will be prefixed with this value. For example, if
	// Prefix is set to "MYAPP", the environment variable "MYAPP_FOO" will be
	// used for the variable "FOO". If not set, no prefix will be used.
	// This is useful for namespacing environment variables in larger applications.
	//nolint:gochecknoglobals
	Prefix = ""
)

Functions

func Help

func Help() string

Help returns a string with the help information for all registered environment variables. The help information includes the name, type, description, and default value (if applicable) for each variable.

func Parse

func Parse() error

Parse parses the environment variables registered with Register. If an error occurs, it will be returned. If ExitOnError is set, the program will exit with code 1 and print the error to stderr.

Types

type Opts

type Opts[T TypeConstraint] struct {
	// Name of the environment variable, as expected in the environment.
	// For example: "LOG_LEVEL".
	Name string
	// Description of the environment variable, as shown in the help message.
	Desc string
	// Default value of the environment variable, if not set in the environment.
	Value T
	// Required indicates if the environment variable is required. A required
	// variable that can't be found in the environment will cause an error.
	Required bool
	// Forces the creation of the variable, *if it does not exist*. This results
	// in setting the environment variable with `os.SetEnv()`.
	Create bool
	// Validates the parsed value.
	Validate func(T) error
	// A list of accepted values for the variable. If set, the value must be one
	// of the accepted values. This is a convenience for the Validate function.
	// If set, the Validate function is ignored.
	AcceptedValues []T
}

Opts is a struct that defines the options for an environment variable.

type TypeConstraint

type TypeConstraint interface {
	~int | ~bool | ~string | ~float64
}

TypeConstraint is a type constraint that allows only int, bool, string, and float64 types. This is used to restrict the types of the environment variables that can be parsed.

type Var

type Var[T TypeConstraint] struct {
	// contains filtered or unexported fields
}

Var is a struct that represents an environment variable. The only public method is Value(), which returns the value of the variable.

func Register

func Register[T TypeConstraint](opts *Opts[T]) *Var[T]

Register a variable with the given options. Returns a pointer to the registered variable.

func (*Var[T]) Value

func (v *Var[T]) Value() T

Value returns the parsed value of the environment variable. Raises a panic if called prior to `Parse()`.

Directories

Path Synopsis
examples
basic command
complex command
prefix command

Jump to

Keyboard shortcuts

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