env

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Dec 11, 2024 License: Apache-2.0, MIT Imports: 9 Imported by: 0

README

go-env

Package go-env is a micro Go-package that provides a simple and idiomatic way to read environment variables in Go.

Installation

go get -u rodusek.dev/pkg/env

Documentation

Overview

Package env is a small package for managing environment variables.

Unlike the standard os.Getenv approach, this package models itself after the encoding/json package, providing a way to marshal and unmarshal environment variables into a structured format using env tags.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Unmarshal

func Unmarshal(out any, opts ...UnmarshalOption) error

Unmarshal reads values from the current environment and parses values into the provided output struct.

Fields on the output struct are interpreted based on `env` tag options which defines the variable key to read from, and any additional options. If this tag is not set, the field name is converted to screaming snake case and used instead (e.g. the field `ProjectName` would use the environment variable `PROJECT_NAME`). Unexported fields are ignored.

A nil `out` parameter is valid and will return nil without error.

This function supports parsing values from the environment for the following types:

This makes use of the `env` tag to specify the environment variable key to read from.

Fields may be marked as required by adding the `required` option to the tag. Slices may have custom separators (default is ',') that may be specified with the `sep` option. For example:

type Environment struct {
	ProjectName string        `env:"PROJECT_NAME,required"`
	Timeout     time.Duration `env:"TIMEOUT"`
	Path        []string      `env:"PATH,required,sep=;"`
}

On error, this function may return one of the following error types:

Example
package main

import (
	"fmt"
	"log"
	"os"
	"time"

	"rodusek.dev/pkg/env"
)

func main() {
	type Environment struct {
		ProjectName string        `env:"PROJECT_NAME,required"`
		Timeout     time.Duration `env:"TIMEOUT"`
		Path        []string      `env:"PATH,required,sep=;"`
	}

	os.Setenv("PROJECT_NAME", "example")
	environment := Environment{
		Timeout: 5 * time.Second, // Setting a default for if not specified
	}
	if err := env.Unmarshal(&environment); err != nil {
		log.Fatalf("failed to unmarshal environment: %v", err)
	}
	fmt.Println(environment.ProjectName, environment.Timeout)
}
Output:
example 5s

Types

type Environment

type Environment map[string]Value

Environment is a map of environment variables.

This map is a simple key-value store where the key is the environment variable name and the value is the environment variable value. It may be used to unmarshal values without requiring the real environment to be modified, such as through the dotenv sub-package.

This type is not thread-safe. If you need to write to the access while concurrently reading it, you should use a mutex to protect it.

func Load

func Load() Environment

Load the current environment variables into a new Environment instance.

The returned map will contain all the elements returned from os.Environ.

func New

func New() Environment

New creates a new empty environment.

func (Environment) Contains

func (e Environment) Contains(key string) bool

Contains returns true if the environment variable with the given key exists.

func (Environment) Export

func (e Environment) Export()

Export sets the environment variables in the current process.

func (Environment) ExportCmd

func (e Environment) ExportCmd(cmd *exec.Cmd)

ExportCmd sets the environment variables into the specified subprocess command object.

func (Environment) Get

func (e Environment) Get(key string) Value

Get the value of the environment variable with the given key, falling back to the real environment as if by using os.Getenv.

Note: To search this without falling back to os.Getenv, use the map access notation instead:

value := env[key]

func (Environment) Lookup

func (e Environment) Lookup(key string) (value Value, ok bool)

Lookup the value of the environment variable with the given key.

If the environment variable does not exist, it will be looked up in the real environment using os.LookupEnv. If it still does not exist, the second return value will be false.

Note: To search this without falling back to os.LookupEnv, use the map access notation instead:

value, ok := env[key]

func (*Environment) Set

func (e *Environment) Set(key string, value Value)

Set the value of the environment variable with the given key.

func (Environment) Unmarshal

func (e Environment) Unmarshal(out any, opts ...UnmarshalOption) error

Unmarshal the environment variables into the given struct. See the documentation for Unmarshal for more details on what can be returned from this function.

func (Environment) Unset

func (e Environment) Unset(key string)

Unset the environment variable with the given key.

type InvalidTagOptionError

type InvalidTagOptionError struct {
	// Key is the environment variable key that caused the error.
	Key string

	// Option is the tag option that caused the error.
	Option string

	// Type is the type of the field the error occurred on.
	Type reflect.Type

	// Field is the struct field that caused the error. This is nil if the type
	// is not a struct field.
	Field *reflect.StructField
}

InvalidTagOptionError is an error that occurs when an invalid tag option is used in a struct field tag.

func (*InvalidTagOptionError) Error

func (e *InvalidTagOptionError) Error() string

type InvalidTypeError

type InvalidTypeError struct {
	// Key is the environment variable key assigned to the type.
	Key string

	// Type is the type that caused the error.
	Type reflect.Type

	// Field is the struct field that caused the error. This is nil if the type
	// is not a struct field.
	Field *reflect.StructField
}

InvalidTypeError is an error that occurs when an unsupported type is used. This can occur when a struct field is not a pointer or when a struct field is not a supported type.

func (*InvalidTypeError) Error

func (e *InvalidTypeError) Error() string

type ParseError

type ParseError struct {
	// Key is the environment variable key that caused the error.
	Key string

	// Value is the value that caused the error.
	Value string

	// Type is the type that caused the error.
	Type reflect.Type

	// Err is the underlying error that was triggered during parsing.
	Err error
}

ParseError is an error that occurs when a value cannot be parsed from an environment variable.

func (*ParseError) Error

func (e *ParseError) Error() string

func (*ParseError) Unwrap

func (e *ParseError) Unwrap() error

type RequirementError

type RequirementError struct {
	Key  string
	Type reflect.Type
}

RequirementError is an error that occurs when a required environment variable is missing.

func (*RequirementError) Error

func (e *RequirementError) Error() string

type UnmarshalOption

type UnmarshalOption interface {
	// contains filtered or unexported methods
}

UnmarshalOption is an option that can be passed to the Unmarshal or Environment.Unmarshal functions.

func Separator

func Separator(sep string) UnmarshalOption

Separator returns an UnmarshalOption that sets the default separator for splitting values for slice values.

This is the _only_ way to set a custom separator when using Value's unmarshal functionality, since values are not part of a struct and therefore cannot provide the `env` sep tag.

type Unmarshaler

type Unmarshaler interface {
	// UnmarshalEnv unmarshals the provided value from an environment string into
	// the implementing type.
	UnmarshalEnv(value []byte) error
}

Unmarshaler is an interface that allows for custom unmarshaling of environment variables.

type Value

type Value string

Value represents an environment variable value, and provides basic utilities for converting to commonly used types.

func (Value) Bool

func (v Value) Bool() (bool, error)

Bool returns the value as a bool and returns any errors that may occur. See Unmarshal for more details on the possible errors that may be returned.

func (Value) Duration

func (v Value) Duration() (time.Duration, error)

Duration returns the value as a time.Duration and returns any errors that may occur. See Unmarshal for more details on the possible errors that may be returned.

func (Value) Float32

func (v Value) Float32() (float32, error)

Float32 returns the value as a float32 and returns any errors that may occur. See Unmarshal for more details on the possible errors that may be returned.

func (Value) Float64

func (v Value) Float64() (float64, error)

Float64 returns the value as a float64 and returns any errors that may occur. See Unmarshal for more details on the possible errors that may be returned.

func (Value) Int

func (v Value) Int() (int, error)

Int returns the value as an int and returns any errors that may occur. See Unmarshal for more details on the possible errors that may be returned.

func (Value) Int8

func (v Value) Int8() (int8, error)

Int8 returns the value as an int8 and returns any errors that may occur. See Unmarshal for more details on the possible errors that may be returned.

func (Value) Int16

func (v Value) Int16() (int16, error)

Int16 returns the value as an int16 and returns any errors that may occur. See Unmarshal for more details on the possible errors that may be returned.

func (Value) Int32

func (v Value) Int32() (int32, error)

Int32 returns the value as an int32 and returns any errors that may occur. See Unmarshal for more details on the possible errors that may be returned.

func (Value) Int64

func (v Value) Int64() (int64, error)

Int64 returns the value as an int64 and returns any errors that may occur. See Unmarshal for more details on the possible errors that may be returned.

func (Value) String

func (v Value) String() string

String returns the value as a string.

func (Value) Time

func (v Value) Time() (time.Time, error)

Time returns the value as a time.Time and returns any errors that may occur. See Unmarshal for more details on the possible errors that may be returned.

func (Value) Uint

func (v Value) Uint() (uint, error)

Uint returns the value as an uint and returns any errors that may occur. See Unmarshal for more details on the possible errors that may be returned.

func (Value) Uint8

func (v Value) Uint8() (uint8, error)

Uint8 returns the value as an uint8 and returns any errors that may occur. See Unmarshal for more details on the possible errors that may be returned.

func (Value) Uint16

func (v Value) Uint16() (uint16, error)

Uint16 returns the value as an uint16 and returns any errors that may occur. See Unmarshal for more details on the possible errors that may be returned.

func (Value) Uint32

func (v Value) Uint32() (uint32, error)

Uint32 returns the value as an uint32 and returns any errors that may occur. See Unmarshal for more details on the possible errors that may be returned.

func (Value) Uint64

func (v Value) Uint64() (uint64, error)

Uint64 returns the value as an uint64 and returns any errors that may occur. See Unmarshal for more details on the possible errors that may be returned.

func (Value) Unmarshal

func (v Value) Unmarshal(value any, opts ...UnmarshalOption) error

Unmarshal the value into the given type.

See Unmarshal for more details on what can be returned from this function.

Jump to

Keyboard shortcuts

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