env

package module
v0.4.3 Latest Latest
Warning

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

Go to latest
Published: Nov 30, 2020 License: MIT Imports: 13 Imported by: 0

README

env

Credit

This repo is a heavily modified version of env by https://github.com/caarlos0 . Also major portions we adapted from github.com/joho/godotenv.

env utility functions

This repo provides some simple utilities for dealing with environment variables. There are some basic functions that are simple wrappers to the "os" package's env functions. These include:

err   = env.Set("KEY", "secret_key")
err   = env.Unset("KEY")
value = env.Get("OTHER_KEY")
value = env.GetOr("OTHER_KEY", "value returned if OTHER_KEY does not exist")
value = env.MustGet("KEY")  // panics if KEY does not exist

Parse environment vars into a struct

A much more powerful approach is to populate an annotated struct with values from the environment.

Take the following example:

type ClientConfig struct {
	Endpoint                  []string      `env:"ENDPOINT" required:"true"`
	HealthCheck               bool          `env:"HEALTH_CHECK" envDefault:"true"`
	HealthCheckTimeout        time.Duration `env:"HEALTH_CHECK_TIMEOUT" envDefault:"1s"`
}

This anotated struct can then be populated with the appropiate environment variables but using the following command:

	cfg := ClientConfig{}
	err := env.Parse(&cfg)

Using a prefix

If the struct you are populating is part of a library you may want to have parse the same struct but with different values. You can do this by using a prfic when parsing.

	cfg := ClientConfig{}
	err := env.ParseWithPrefix(&cfg, "CLIENT2_")

In this case the parser would look for the envionment variables CLIENT2_ENDPOINT, CLIENT2_HEALTH_CHECK, etc.

Supported types and defaults

The environment variables are Parsed to go into the appropiate types (or an err is thrown if it can not do so). This sames you from writing a some basic validations on envirnment varaibles.

The library has built-in support for the following types:

  • string
  • int
  • uint
  • int64
  • bool
  • float32
  • float64
  • time.Duration
  • url.URL
  • []string
  • []int
  • []bool
  • []float32
  • []float64
  • []time.Duration
  • []url.URL
Optional tags

The required tag will cause an error if the environment variable does not exist: `env:"ENDPOINT" required:"true"`

The envDefault tag will allow you to provide a default value to use if the environment variable does not exist: `env:"HEALTH_CHECK" envDefault:"true"`

When assigning to a slice type the "," is used to seperate fields. You can override this with the envSeparator:":" tag to use some other character.

Documentation

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrNotAStructPtr is returned if you pass something that is not a pointer to a
	// Struct to Parse
	ErrNotAStructPtr = errors.New("Expected a pointer to a Struct")
	// ErrUnsupportedType if the struct field type is not supported by env
	ErrUnsupportedType = errors.New("Type is not supported")
	// ErrUnsupportedSliceType if the slice element type is not supported by env
	ErrUnsupportedSliceType = errors.New("Unsupported slice type")
	// OnEnvVarSet is an optional convenience callback, such as for logging purposes.
	// If not nil, it's called after successfully setting the given field from the given value.
	OnEnvVarSet func(reflect.StructField, string)
)

Functions

func Get added in v0.2.0

func Get(key string) string

Get - get an environment variable, empty string if does not exist

func GetBool added in v0.2.6

func GetBool(key string) (bool, error)

GetBool - get an environment variable as boolean

func GetDuration added in v0.4.0

func GetDuration(key string) (time.Duration, error)

GetDuration - get an environment variable as time.Duration

func GetFloat32 added in v0.2.7

func GetFloat32(key string) (float32, error)

GetFloat32 - get an environment variable as float32

func GetFloat64 added in v0.4.0

func GetFloat64(key string) (float64, error)

GetFloat64 - get an environment variable as float64

func GetInt added in v0.2.6

func GetInt(key string) (int, error)

GetInt - get an environment variable as int

func GetInt64 added in v0.4.0

func GetInt64(key string) (int64, error)

GetInt64 - get an environment variable as int64

func GetOr added in v0.2.0

func GetOr(key, defaultValue string) string

GetOr - get an environment variable or return default value if does not exist

func GetOrBool added in v0.2.6

func GetOrBool(key string, defaultValue bool) bool

GetOrBool - get an environment variable or return default value if does not exist

func GetOrDuration added in v0.4.0

func GetOrDuration(key string, defaultValue string) time.Duration

GetOrDuration - get an environment variable or return default value if does not exist

func GetOrFloat32 added in v0.2.7

func GetOrFloat32(key string, defaultValue float32) float32

GetOrFloat32 - get an environment variable or return default value if does not exist

func GetOrFloat64 added in v0.4.0

func GetOrFloat64(key string, defaultValue float64) float64

GetOrFloat64 - get an environment variable or return default value if does not exist

func GetOrInt added in v0.2.6

func GetOrInt(key string, defaultValue int) int

GetOrInt - get an environment variable or return default value if does not exist

func GetOrInt64 added in v0.4.0

func GetOrInt64(key string, defaultValue int64) int64

GetOrInt64 - get an environment variable or return default value if does not exist

func GetOrUint added in v0.2.6

func GetOrUint(key string, defaultValue uint) uint

GetOrUint - get an environment variable or return default value if does not exist

func GetOrUint64 added in v0.4.0

func GetOrUint64(key string, defaultValue uint64) uint64

GetOrUint64 - get an environment variable or return default value if does not exist

func GetOrUrl added in v0.4.0

func GetOrUrl(key string, defaultValue string) *url.URL

GetOrUrl - get an environment variable or return default value if does not exist

func GetUint added in v0.2.6

func GetUint(key string) (uint, error)

GetUint - get an environment variable as uint

func GetUint64 added in v0.4.0

func GetUint64(key string) (uint64, error)

GetUint64 - get an environment variable as uint

func GetUrl added in v0.4.0

func GetUrl(key string) (*url.URL, error)

GetUrl - get an environment variable as url.URL

func Load added in v0.2.5

func Load(filenames ...string) (err error)

Load will read your env file(s) and load them into ENV for this process.

Call this function as close as possible to the start of your program (ideally in main)

If you call Load without any args it will default to loading .env in the current path

You can otherwise tell it which files to load (there can be more than one) like

err := env.Load("fileone", "filetwo")

It's important to note that it WILL NOT OVERRIDE an env variable that already exists - consider the .env file to set dev vars or sensible defaults

func Marshal added in v0.2.5

func Marshal(envMap map[string]string) (string, error)

Marshal outputs the given environment as a dotenv-formatted environment file. Each line is in the format: KEY="VALUE" where VALUE is backslash-escaped.

func MustGet added in v0.2.0

func MustGet(key string) string

MustGet - get an environment variable or panic if does not exist

func MustGetBool added in v0.2.6

func MustGetBool(key string) bool

MustGetBool - get an environment variable or panic if does not exist

func MustGetDuration added in v0.4.0

func MustGetDuration(key string) time.Duration

MustGetDuration - get an environment variable or panic if does not exist

func MustGetFloat32 added in v0.2.7

func MustGetFloat32(key string) float32

MustGetUFloat32 - get an environment variable or panic if does not exist

func MustGetFloat64 added in v0.4.0

func MustGetFloat64(key string) float64

MustGetUFloat64 - get an environment variable or panic if does not exist

func MustGetInt added in v0.2.6

func MustGetInt(key string) int

MustGetInt - get an environment variable or panic if does not exist

func MustGetInt64 added in v0.4.0

func MustGetInt64(key string) int64

MustGetInt64 - get an environment variable or panic if does not exist

func MustGetUint added in v0.2.6

func MustGetUint(key string) uint

MustGetUint - get an environment variable or panic if does not exist

func MustGetUint64 added in v0.4.0

func MustGetUint64(key string) uint64

MustGetUint64 - get an environment variable or panic if does not exist

func MustGetUrl added in v0.4.0

func MustGetUrl(key string) *url.URL

MustGetUrl - get an environment variable or panic if does not exist

func MustLoad added in v0.2.7

func MustLoad(filenames ...string)

MustLoad will read your env file(s) and load them into ENV for this process.

Call this function as close as possible to the start of your program (ideally in main)

If you call Load without any args it will default to loading .env in the current path. If there are any errors the function will panic.

You can otherwise tell it which files to load (there can be more than one) like

env.MustLoad("fileone", "filetwo")

It's important to note that it WILL NOT OVERRIDE an env variable that already exists - consider the .env file to set dev vars or sensible defaults

func MustOverload added in v0.2.7

func MustOverload(filenames ...string)

MustOverload will read your env file(s) and load them into ENV for this process.

Call this function as close as possible to the start of your program (ideally in main)

If you call Overload without any args it will default to loading .env in the current path

You can otherwise tell it which files to load (there can be more than one) like

env.MustOverload("fileone", "filetwo")

It's important to note this WILL OVERRIDE an env variable that already exists - consider the .env file to forcefilly set all vars.

func Overload added in v0.2.5

func Overload(filenames ...string) (err error)

Overload will read your env file(s) and load them into ENV for this process.

Call this function as close as possible to the start of your program (ideally in main)

If you call Overload without any args it will default to loading .env in the current path

You can otherwise tell it which files to load (there can be more than one) like

err := env.Overload("fileone", "filetwo")

It's important to note this WILL OVERRIDE an env variable that already exists - consider the .env file to forcefilly set all vars.

func Parse

func Parse(v interface{}) error

Parse parses a struct containing `env` tags and loads its values from environment variables.

Example
type config struct {
	Home         string `env:"HOME"`
	Port         int    `env:"PORT" envDefault:"3000"`
	IsProduction bool   `env:"PRODUCTION"`
}
os.Setenv("HOME", "/tmp/fakehome")
cfg := config{}
_ = Parse(&cfg)
fmt.Println(cfg)
Output:

{/tmp/fakehome 3000 false}

func ParseIO added in v0.2.5

func ParseIO(r io.Reader) (envMap map[string]string, err error)

ParseIO reads an env file from io.Reader, returning a map of keys and values.

func ParseWithFuncs

func ParseWithFuncs(v interface{}, funcMap CustomParsers) error

ParseWithFuncs is the same as `Parse` except it also allows the user to pass in custom parsers.

func ParseWithPrefix

func ParseWithPrefix(v interface{}, prefix string) error

ParseWithPrefix parses a struct containing `env` tags and loads its values from environment variables. The actual env vars looked up include the passed in prefix.

func ParseWithPrefixFuncs

func ParseWithPrefixFuncs(v interface{}, prefix string, funcMap CustomParsers) error

ParseWithPrefixFuncs is the same as `ParseWithPrefix` except it also allows the user to pass in custom parsers.

func Read added in v0.2.5

func Read(filenames ...string) (envMap map[string]string, err error)

Read all env (with same file loading semantics as Load) but return values as a map rather than automatically writing values into env

func Set added in v0.2.0

func Set(key, value string) error

Set - sets an environment variable

func Unmarshal added in v0.2.5

func Unmarshal(str string) (envMap map[string]string, err error)

Unmarshal reads an env file from a string, returning a map of keys and values.

func Unset added in v0.2.0

func Unset(key string) error

Unset - unsets an environment variable

func Write added in v0.2.5

func Write(envMap map[string]string, filename string) error

Write serializes the given environment and writes it to a file

Types

type CustomParsers

type CustomParsers map[reflect.Type]ParserFunc

CustomParsers is a friendly name for the type that `ParseWithFuncs()` accepts

type ParserFunc

type ParserFunc func(v string) (interface{}, error)

ParserFunc defines the signature of a function that can be used within `CustomParsers`

Jump to

Keyboard shortcuts

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