envconfig

package module
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Apr 29, 2024 License: ISC Imports: 12 Imported by: 0

README

go-envconfig

go reference pipeline status coverage report

Yet another library for populating struct fields from environment variables.

Usage

package main

import (
  "gitlab.com/cptpackrat/go-envconfig"
)

type MyConfig struct {
  Foo string `env:"FOO"`
  Bar int    `env:"BAR"`
  Boo bool   `env:"BOO"`
}

func main () {
  var cfg MyConfig
  if err := envconfig.Populate(&cfg); err != nil {
    log.Fatal(err)
  } else {
    log.Printf("Foo=%s\nBar=%d\nBoo=%t\n", cfg.Foo, cfg.Bar, cfg.Boo)
  }
}
$ go build -o app
$ FOO=test BAR=1234 BOO=true ./app
Foo=test
Bar=1234
Boo=true

Configuration

Use the env struct tag to associate struct fields with environment variables.

Required Variables

If a field is tagged as required an error will be returned if its associated variable is not present.

type MyConfig struct {
  Foo string `env:"FOO,required"`
  Bar int    `env:"BAR,required"`
  Boo bool   `env:"BOO"`
}
$ go build -o app
$ ./app
configuration errors:
- FOO is not set
- BAR is not set
Default Values

Default values can be specified by initialising the struct before passing it to Populate; struct fields are not modified unless their associated environment variables are present.

func main () {
  cfg := MyConfig{
    Foo: "default",
  }
  if err := envconfig.Populate(&cfg); err != nil {
    log.Fatal(err)
  } else {
    log.Printf("Foo=%s\nBar=%d\nBoo=%t\n", cfg.Foo, cfg.Bar, cfg.Boo)
  }
}
$ go build -o app
$ BAR=1234 BOO=true ./app
Foo=default
Bar=1234
Boo=true
Nested Field Names

Nested structs can be marked with the "prefix" option to prepend their name onto fields within when populating them from the environment.

type Config struct {
  A string `env:"ENVCONFIG_A"`
  B int    `env:"ENVCONFIG_B"`
}
type MyConfig struct {
  Config `env:"MY_,prefix"` // populates from MY_ENVCONFIG_A and MY_ENVCONFIG_B
}
Supported Types

Supports all basic types including bool, string, and all int*, uint*, float*, and complex* variants.

Custom Types

Custom types can be implement their own behaviour via the UnmarshalEnv interface.

type FileBytes []byte

func (f *FileBytes) UnmarshalEnv(_, name string) error {
  data, err := os.ReadFile(name)
  if err != nil {
    return err
  }
  *f = data
  return nil
}

When used as fields in a struct, the example type defined above will be populated with the contents of the file pointed to by its associated variable, rather than the contents of the variable itself.

type MyConfig struct {
  Key  FileBytes `env:"KEY,required"`
  Cert FileBytes `env:"CERT,required"`
}

Documentation

Overview

Package envconfig implements functionality to unmarshal environment variables into the fields of a struct. Fields to be populated are selected via the "env" struct tag, which is used to specify the name of the associated environment variable and any options.

type MyConfig struct {
  A string `env:"ENVCONFIG_A,required"` // accepts any value, must be set
  B int    `env:"ENVCONFIG_B"`          // accepts valid int per strconv.ParseInt, or unset
  C bool   `env:"ENVCONFIG_C"`          // accepts valid bool per strconv.ParseBool, or unset
}

Fields without an "env" tag will be ignored, and nested structs will be populated recursively.

type MyConfig struct {
  A string `env:"ENVCONFIG_A"` // accepts any value, or unset
  B struct {
    C int  `env:"ENVCONFIG_C"` // accepts valid int per strconv.ParseInt, or unset
    D bool                     // ignored by envconfig
  }
}

Default values are specified by initialising the struct before calling Populate; struct fields are not modified unless their associated environment variables are present.

var config = struct{
  A string `env:"ENVCONFIG_A"`
} {
  A: "foo", // default value will remain if ENVCONFIG_A is not set
}
envconfig.Populate(&config)

Nested structs can be marked with the "prefix" option to prepend their name onto fields within when populating them from the environment.

	type Config struct {
		A string `env:"ENVCONFIG_A"`
		B int    `env:"ENVCONFIG_B"`
	}
	type MyConfig struct {
		Config `env:"MY_,prefix"` // populates from MY_ENVCONFIG_A and MY_ENVCONFIG_B
 }

Supports all basic types including bool, string, and all integral, floating-point and complex number types. Custom types can be implement their own behaviour via the UnmarshalEnv interface.

type FileBytes []byte

func (f *FileBytes) UnmarshalEnv(_, name string) error {
  data, err := os.ReadFile(name)
  if err != nil {
    return err
  }
  *f = data
  return nil
}

When used as fields in a struct, the example type defined above will be populated with the contents of the file pointed to by its associated variable, rather than the contents of the variable itself.

type MyConfig struct {
  Key  FileBytes `env:"KEY,required"`  // contents of file pointed to by KEY
  Cert FileBytes `env:"CERT,required"` // contents of file pointed to by CERT
}

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Populate

func Populate(cfg interface{}) error

Populate attempts to populate tagged fields in the provided struct from the process environment.

func PopulateFrom

func PopulateFrom(cfg interface{}, env Env) error

Populate attempts to populate tagged fields in the provided struct from a custom environment.

Types

type CSV added in v1.2.0

type CSV []string

CSV is a utility type that unmarhsals an environment variable as a list of comma-separated values.

func (*CSV) UnmarshalEnv added in v1.2.0

func (c *CSV) UnmarshalEnv(key, val string) error

type Env

type Env interface {
	// LookupEnv returns the value of the given key in this environment,
	// and a boolean indicating if the key exists in this environment.
	LookupEnv(key string) (string, bool)
}

Env represents an interface to an environment-like key/value store.

type FieldError

type FieldError struct {
	Var string // Environment variable associated with field.
	Msg string // Reason why populating this field failed.
	Err error  // Specific error underlying this failure; may be nil.
}

A FieldError represents a failure to populate a single struct field.

func (FieldError) Error

func (err FieldError) Error() string

func (FieldError) Unwrap

func (err FieldError) Unwrap() error

type PopulateError

type PopulateError []FieldError

A PopulateError represents a failure to populate a struct, and encapsulates all errors encountered during the attempt.

func (PopulateError) Error

func (errs PopulateError) Error() string

type ReadFile added in v1.2.0

type ReadFile struct {
	Name string // File name.
	Data []byte // File contents.
}

ReadFile is a utility type that unmarshals an environment variable as a path to a file which is automatically read.

func (*ReadFile) UnmarshalEnv added in v1.2.0

func (f *ReadFile) UnmarshalEnv(key, val string) error

type ReadFileJSON added in v1.2.0

type ReadFileJSON[T any] struct {
	Name string // File name.
	Data T      // File contents.
}

ReadFileJSON is a utility type that unmarshals an environment variable as a path to a JSON file which is automatically read, and its contents unmarshaled into a value of type T.

func (*ReadFileJSON[T]) UnmarshalEnv added in v1.2.0

func (f *ReadFileJSON[T]) UnmarshalEnv(key, val string) error

type URL added in v1.2.0

type URL struct {
	url.URL
}

URL is a utility type that unmarshals an environment variable as a URL.

func (*URL) UnmarshalEnv added in v1.2.0

func (u *URL) UnmarshalEnv(key, val string) error

type UnmarshalEnv added in v1.1.0

type UnmarshalEnv interface {
	// UnmarshalEnv is responsible for populating its associated value from the
	// given environment variable, or returning an error if it cannot.
	// This method will only work if implemented for pointer receivers.
	UnmarshalEnv(key, value string) error
}

UnmarshalEnv represents a field with customised unmarshalling behaviour.

Jump to

Keyboard shortcuts

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