env

package module
v5.1.4 Latest Latest
Warning

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

Go to latest
Published: May 3, 2019 License: MIT Imports: 8 Imported by: 8

README

env

Build Status Coverage Status

Simple lib to parse envs to structs in Go.

Example

A very basic example:

package main

import (
	"fmt"
	"time"

	"github.com/caarlos0/env"
)

type config struct {
	Home         string        `env:"HOME"`
	Port         int           `env:"PORT" envDefault:"3000"`
	IsProduction bool          `env:"PRODUCTION"`
	Hosts        []string      `env:"HOSTS" envSeparator:":"`
	Duration     time.Duration `env:"DURATION"`
	TempFolder   string        `env:"TEMP_FOLDER" envDefault:"${HOME}/tmp" envExpand:"true"`
}

func main() {
	cfg := config{}
	if err := env.Parse(&cfg); err != nil {
		fmt.Printf("%+v\n", err)
	}

	fmt.Printf("%+v\n", cfg)
}

You can run it like this:

$ PRODUCTION=true HOSTS="host1:host2:host3" DURATION=1s go run main.go
{Home:/your/home Port:3000 IsProduction:true Hosts:[host1 host2 host3] Duration:1s}

Go modules

If you're using go modules, you can update to v5 by issuing the following command:

go get -u github.com/caarlos0/env/v5

Then, on your code, use github.com/caarlos0/env/v5 instead of github.com/caarlos0/env as the import path.

Supported types and defaults

The following types are supported out of the box:

  • string
  • *string
  • []string
  • bool
  • *bool
  • []bool
  • int
  • *int
  • []int
  • int8
  • *int8
  • []int8
  • int16
  • []int16
  • *int16
  • int32
  • []int32
  • *int32
  • int64
  • []int64
  • *int64
  • uint
  • []uint
  • *uint
  • uint8
  • []uint8
  • *uint8
  • uint16
  • []uint16
  • *uint16
  • uint32
  • []uint32
  • *uint32
  • uint64
  • []uint64
  • *uint64
  • float32
  • *float32
  • []float32
  • float64
  • *float64
  • []float64
  • string
  • []string
  • time.Duration
  • []time.Duration
  • encoding.TextUnmarshaler
  • *encoding.TextUnmarshaler
  • []encoding.TextUnmarshaler
  • []*encoding.TextUnmarshaler
  • url.URL
  • []url.URL

You can also use/define a custom parser func for any other type you want.

If you set the envDefault tag for something, this value will be used in the case of absence of it in the environment. If you don't do that AND the environment variable is also not set, the zero-value of the type will be used: empty for strings, false for bools, 0 for ints and so forth.

By default, slice types will split the environment value on ,; you can change this behavior by setting the envSeparator tag.

If you set the envExpand tag, environment variables (either in ${var} or $var format) in the string will be replaced according with the actual value of the variable.

Unexported fields are ignored.

Custom Parser Funcs

If you have a type that is not supported out of the box by the lib, you are able to use (or define) and pass custom parsers (and their associated reflect.Type) to the env.ParseWithFuncs() function.

In addition to accepting a struct pointer (same as Parse()), this function also accepts a env.CustomParsers arg that under the covers is a map[reflect.Type]env.ParserFunc.

env also ships with some pre-built custom parser funcs for common types. You can check them out here.

Required fields

The env tag option required (e.g., env:"tagKey,required") can be added to ensure that some environment variable is set. In the example above, an error is returned if the config struct is changed to:

type config struct {
    Home         string   `env:"HOME"`
    Port         int      `env:"PORT" envDefault:"3000"`
    IsProduction bool     `env:"PRODUCTION"`
    Hosts        []string `env:"HOSTS" envSeparator:":"`
    SecretKey    string   `env:"SECRET_KEY,required"`
}

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("env: expected a pointer to a Struct")
)

nolint: gochecknoglobals

Functions

func Parse

func Parse(v interface{}) error

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

Example
type inner struct {
	Foo string `env:"FOO" envDefault:"foobar"`
}
type config struct {
	Home         string `env:"HOME,required"`
	Port         int    `env:"PORT" envDefault:"3000"`
	IsProduction bool   `env:"PRODUCTION"`
	Inner        inner
}
os.Setenv("HOME", "/tmp/fakehome")
var cfg config
if err := Parse(&cfg); err != nil {
	fmt.Println("failed:", err)
}
fmt.Printf("%+v", cfg)
Output:

{Home:/tmp/fakehome Port:3000 IsProduction:false Inner:{Foo:foobar}}

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.

Example
type config struct {
	ExampleURL url.URL `env:"EXAMPLE_URL" envDefault:"https://google.com"`
}
var cfg config
if err := ParseWithFuncs(&cfg, CustomParsers{
	parsers.URLType: parsers.URLFunc,
}); err != nil {
	fmt.Println("failed:", err)
}
fmt.Println(cfg.ExampleURL.String())
Output:

https://google.com

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`

Directories

Path Synopsis
Package parsers contains custom parser funcs for common, non-built-in types
Package parsers contains custom parser funcs for common, non-built-in types

Jump to

Keyboard shortcuts

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