envmodel

package module
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Apr 11, 2021 License: MIT Imports: 11 Imported by: 0

README

envmodel

Managing configuration data from environment variables using object model.

Usage

Declare model and parse.

package main

import (
	"log"
	"time"

	"github.com/kolatat/envmodel"
)

// Declare the object model
type Config struct {
	Name    string
	Timeout time.Duration
	Debug   bool
}

func main() {
	var cfg Config
	// Parse environment variables into your object
	if _, err := envmodel.Parse(&cfg, &envmodel.Option{
		AppName: "MYAPP",
		DotEnv:  true,
	}); err != nil {
		log.Fatalf("parsing config: %s", err)
	}
}

The parser will read the field names, and convert the PascalCase names into UPPERCASE_SNAKE_CASE names.

Options
Namespace

Namespace - prefixes all key names with the specified namespace. For example, when using Namespace: "DB":

HostName string     => "DB_HOST_NAME"
Database string     => "DB_DATABASE"
DotEnv

DotEnv: true - Additionally loads environment variables from ~.env files. See https://github.com/joho/godotenv.

AppName: "MYAPP" - The environment variable {AppName}_ENV, is checked to establish the runtime environment of the app. If it is empty or unset, a development environment is assumed.

DotEnv will check for and load the following files:

  1. .env.{environment}.local
  2. .env.local
  3. .env.{environment}
  4. .env

Missing files will be skipped, and existing variables take precedence.

Struct Tag

Tag key name: env

package main

import "time"

type Config struct {
	Name    string        `env:"key:DISPLAY"`
	Timeout time.Duration `env:"required,default:5s"`
	Wtv     interface{}   `env:"-"`
}

The env tag is a comma separated list of attributes. Use - and the field will be ignored by the parser. Each attribute can be in the form of a flag attribute, or a key-pair key:value.

  • key:{string} the name of the environment variable to parse from
  • required will throw an error if the variable is not defined and no default is given (an empty string is considered defined)
  • default:{string} the value given here will be use in case the variable is undefined (default is not used if the variable is defined but empty i.e "" - the zero value will be assigned)

References

Documentation

Index

Constants

View Source
const (
	EnvDevelopment = "development"
	EnvTest        = "test"

	EnvKey = "ENV"
)
View Source
const (
	TagKey = "env"
)

Variables

View Source
var (
	// A field is marked as required, but the environment variable of that key is not defined
	ErrRequiredKeyUndefined = errors.New("required key is not defined")

	// The map entry is not specified in the correct format, expects "key:value"
	ErrInvalidMapEntry = errors.New("invalid map entry")

	ErrInvalidTarget   = errors.New("target must be a struct pointer")
	ErrUnsupportedType = errors.New("unsupported data type")
)
View Source
var EnvMask = []string{
	"password",
	"passcode",
	"secret",
	"passphrase",
	"privkey",
	"privatekey",
	"private_key",
	"mongo_uri",
	"access_token",
	"api_key",
}

Functions

func LoadDotEnv

func LoadDotEnv(environment ...*Environment) error

Types

type Environment

type Environment struct {
	EnvKey string
	Env    string
	// contains filtered or unexported fields
}

func NewEnvironment

func NewEnvironment(option ...*Option) *Environment

func Parse

func Parse(obj interface{}, option ...*Option) (*Environment, error)

Parse studies the model of obj, and reads environment variables into its fields.

type Option

type Option struct {
	AppName   string
	DotEnv    bool
	Namespace string
	Logger    *zerolog.Logger
}

type ParseError

type ParseError struct {
	KeyName   string
	FieldName string
	TypeName  string
	Value     string
	Reason    error
}

ParseError occurs during the parsing of a specific struct field. It contains detail about that field, and the reason for the error.

func (*ParseError) Error

func (err *ParseError) Error() string

func (*ParseError) Unwrap

func (err *ParseError) Unwrap() error

type Setter

type Setter interface {
	Set(value string) error
}

Setter is implemented by types can self-deserialize values. Any type that implements flag.Value also implements Setter.

type TagInfo

type TagInfo struct {
	IsDefined bool

	Key string

	Required bool
	Default  string
	// contains filtered or unexported fields
}

func (*TagInfo) IsIgnored

func (t *TagInfo) IsIgnored() bool

Jump to

Keyboard shortcuts

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