envcfg

package module
v0.0.0-...-036a2d8 Latest Latest
Warning

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

Go to latest
Published: Oct 7, 2020 License: MIT Imports: 12 Imported by: 0

README

Tests Lint GoDoc

envcfg

A simple and powerful env config library which also provides generated documentation of your configuration values.

package main

import (
    "encoding/json"
    "github.com/jwilner/envcfg"
    "log"
    "os"
)

func main() {
    cfg := envcfg.New()
    time := cfg.Time("EXAMPLE_TIME optional")
    ints := cfg.IntSlice("EXAMPLE_INT_SLICE comma=: base=16 default=a:b:c | Some info about your super important ints")
    
    descriptions, err := cfg.Result()
    if err != nil {
        log.Fatal(err)
    }

    if len(os.Args) > 1 && os.Args[1] == "--help" {
        _ = json.NewEncoder(os.Stderr).Encode(descriptions)
        // Output:
        //[
        //  {"name": "EXAMPLE_TIME", "type": "time.Time", "optional": true},
        //  {
        //      "name": "EXAMPLE_INT_SIZE", 
        //      "type": "[]int64", 
        //      "params": {"comma": ":", "base": 16}, 
        //      "default": [11, 12, 13],
        //      "comment": "Some info about your super important ints"
        //   }
        //]
        os.Exit(1)
    }
    
    _ = time
    _ = ints
}

Documentation

Overview

Package envcfg is a simple and opinionated library for parsing environment variables and documenting their usage.

The central type is envcfg.Cfg, which can be constructed with envcfg.New. Cfg has a series of parse methods. Each parse method expects the name of the environment variable and a variety of optional parameters.

The optional parameters can be specified either in the primary string following the comment or with type safe options. For example, the following two invocations are functionally identical:

cfg.Int("MY_EXAMPLE_INT", envcfg.IntDefault(10), envcfg.IntBase(16), envcfg.Comment("A really cool int"))

cfg.Int("MY_EXAMPLE_INT default=a base=16 | A really cool int")

After parsing, errors can be checked with `Err`:

if err := cfg.Err(); err != nil {
	log.Fatalf("failed loading config: %v", err)
}

Describe of the config interface can also be printed (e.g. as JSON):

json.NewEncoder(os.Stdout).Encode(cfg.Describe())

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type BoolOpt

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

BoolOpt modifies Bool variable configuration.

func BoolDefault

func BoolDefault(def bool) BoolOpt

BoolDefault specifies a default value for a Bool variable.

type BytesOpt

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

BytesOpt modifies Bytes variable configuration.

func BytesDefault

func BytesDefault(def []byte) BytesOpt

BytesDefault specifies a default value for a Bytes variable.

func BytesNoPadding

func BytesNoPadding(noPadding bool) BytesOpt

BytesNoPadding disables padding for a Bytes variable.

func BytesPadding

func BytesPadding(padding rune) BytesOpt

BytesPadding specifies an alternate padding for a Bytes variable.

func BytesURLSafe

func BytesURLSafe(urlSafe bool) BytesOpt

BytesURLSafe specifies the URL safe form of base64 encoding for a Bytes variable.

type Cfg

type Cfg struct {
	// contains filtered or unexported fields
}

func New

func New(opts ...Option) *Cfg

func (*Cfg) Bool

func (c *Cfg) Bool(docOpts string, opts ...BoolOpt) (v bool)

Bool extracts and parses a bool variable using the options provided.

The first argument must be a string with beginning with the variable name as expected in the process environment. Any other options -- none of which are required -- may either be specified in the remainder of the string or using the type-safe BoolOpts.

Available options:

  • "default" or BoolDefault
  • "optional" or Optional

func (*Cfg) Bytes

func (c *Cfg) Bytes(docOpts string, opts ...BytesOpt) (v []byte)

Bytes extracts and parses a []byte variable using the options provided.

The first argument must be a string with beginning with the variable name as expected in the process environment. Any other options -- none of which are required -- may either be specified in the remainder of the string or using the type-safe BytesOpts.

Available options:

  • "default" or BytesDefault
  • "no_padding" or BytesNoPadding
  • "optional" or Optional
  • "padding" or BytesPadding
  • "url_safe" or BytesURLSafe

func (*Cfg) Describe

func (c *Cfg) Describe() []Description

func (*Cfg) Duration

func (c *Cfg) Duration(docOpts string, opts ...DurationOpt) (v time.Duration)

Duration extracts and parses a time.Duration variable using the options provided.

The first argument must be a string with beginning with the variable name as expected in the process environment. Any other options -- none of which are required -- may either be specified in the remainder of the string or using the type-safe DurationOpts.

Available options:

  • "default" or DurationDefault
  • "optional" or Optional

func (*Cfg) Err

func (c *Cfg) Err() error

func (*Cfg) Float

func (c *Cfg) Float(docOpts string, opts ...FloatOpt) (v float64)

Float extracts and parses a float64 variable using the options provided.

The first argument must be a string with beginning with the variable name as expected in the process environment. Any other options -- none of which are required -- may either be specified in the remainder of the string or using the type-safe FloatOpts.

Available options:

  • "bit_size" or FloatBitSize
  • "default" or FloatDefault
  • "optional" or Optional

func (*Cfg) Has

func (c *Cfg) Has(s string) bool

func (*Cfg) HasNot

func (c *Cfg) HasNot(s string) bool

func (*Cfg) IP

func (c *Cfg) IP(docOpts string, opts ...IPOpt) (v net.IP)

IP extracts and parses a net.IP variable using the options provided.

The first argument must be a string with beginning with the variable name as expected in the process environment. Any other options -- none of which are required -- may either be specified in the remainder of the string or using the type-safe IPOpts.

Available options:

  • "default" or IPDefault
  • "optional" or Optional

func (*Cfg) Int

func (c *Cfg) Int(docOpts string, opts ...IntOpt) (v int64)

Int extracts and parses a int64 variable using the options provided.

The first argument must be a string with beginning with the variable name as expected in the process environment. Any other options -- none of which are required -- may either be specified in the remainder of the string or using the type-safe IntOpts.

Available options:

  • "base" or IntBase
  • "bit_size" or IntBitSize
  • "default" or IntDefault
  • "optional" or Optional
Example
package main

import (
	"encoding/json"
	"fmt"
	"os"

	"github.com/jwilner/envcfg"
)

func main() {
	os.Setenv("EXAMPLE_HEX_INT", "abcdef")
	c := envcfg.New()
	val := c.Int("EXAMPLE_HEX_INT base=16 default=1f | A hex int configuration value")
	desc, err := c.Result()
	fmt.Printf("%v\n", val)
	fmt.Printf("%v\n", err)
	enc := json.NewEncoder(os.Stdout)
	enc.SetIndent("", "    ")
	_ = enc.Encode(desc[0])
}
Output:

11259375
<nil>
{
    "name": "EXAMPLE_HEX_INT",
    "type": "int64",
    "optional": false,
    "default": 31,
    "params": {
        "base": 16
    },
    "comment": "A hex int configuration value"
}

func (*Cfg) IntSlice

func (c *Cfg) IntSlice(docOpts string, opts ...IntSliceOpt) (v []int64)

IntSlice extracts and parses a []int64 variable using the options provided.

The first argument must be a string with beginning with the variable name as expected in the process environment. Any other options -- none of which are required -- may either be specified in the remainder of the string or using the type-safe IntSliceOpts.

Available options:

  • "base" or IntSliceBase
  • "bit_size" or IntSliceBitSize
  • "comma" or IntSliceComma
  • "default" or IntSliceDefault
  • "optional" or Optional

func (*Cfg) Result

func (c *Cfg) Result() ([]Description, error)

func (*Cfg) String

func (c *Cfg) String(docOpts string, opts ...StringOpt) (v string)

String extracts and parses a string variable using the options provided.

The first argument must be a string with beginning with the variable name as expected in the process environment. Any other options -- none of which are required -- may either be specified in the remainder of the string or using the type-safe StringOpts.

Available options:

  • "default" or StringDefault
  • "optional" or Optional

func (*Cfg) StringSlice

func (c *Cfg) StringSlice(docOpts string, opts ...StringSliceOpt) (v []string)

StringSlice extracts and parses a []string variable using the options provided.

The first argument must be a string with beginning with the variable name as expected in the process environment. Any other options -- none of which are required -- may either be specified in the remainder of the string or using the type-safe StringSliceOpts.

Available options:

  • "comma" or StringSliceComma
  • "default" or StringSliceDefault
  • "optional" or Optional

func (*Cfg) Time

func (c *Cfg) Time(docOpts string, opts ...TimeOpt) (v time.Time)

Time extracts and parses a time.Time variable using the options provided.

The first argument must be a string with beginning with the variable name as expected in the process environment. Any other options -- none of which are required -- may either be specified in the remainder of the string or using the type-safe TimeOpts.

Available options:

  • "default" or TimeDefault
  • "layout" or TimeLayout
  • "optional" or Optional

func (*Cfg) Uint

func (c *Cfg) Uint(docOpts string, opts ...UintOpt) (v uint64)

Uint extracts and parses a uint64 variable using the options provided.

The first argument must be a string with beginning with the variable name as expected in the process environment. Any other options -- none of which are required -- may either be specified in the remainder of the string or using the type-safe UintOpts.

Available options:

  • "base" or UintBase
  • "bit_size" or UintBitSize
  • "default" or UintDefault
  • "optional" or Optional

type DefaultValDescription

type DefaultValDescription struct {
	Value interface{}
}

func (DefaultValDescription) MarshalJSON

func (d DefaultValDescription) MarshalJSON() ([]byte, error)

type Description

type Description struct {
	Name     string                 `json:"name"`
	Type     string                 `json:"type"`
	Optional bool                   `json:"optional"`
	Default  *DefaultValDescription `json:"default,omitempty"`
	Params   interface{}            `json:"params,omitempty"`
	Comment  string                 `json:"comment,omitempty"`
}

type DurationOpt

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

DurationOpt modifies Duration variable configuration.

func DurationDefault

func DurationDefault(def time.Duration) DurationOpt

DurationDefault specifies a default value for a Duration variable.

type FloatOpt

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

FloatOpt modifies Float variable configuration.

func FloatBitSize

func FloatBitSize(bitSize int) FloatOpt

FloatBitSize specifies the bit size to use for a Float variable.

func FloatDefault

func FloatDefault(def float64) FloatOpt

FloatDefault specifies a default value for a Float variable.

type IPOpt

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

IPOpt modifies IP variable configuration.

func IPDefault

func IPDefault(def net.IP) IPOpt

IPDefault specifies a default value for a IP variable.

type IntOpt

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

IntOpt modifies Int variable configuration.

func IntBase

func IntBase(base int) IntOpt

IntBase specifies the base to use for a Int variable.

func IntBitSize

func IntBitSize(bitSize int) IntOpt

IntBitSize specifies the bit size to use for a Int variable.

func IntDefault

func IntDefault(def int64) IntOpt

IntDefault specifies a default value for a Int variable.

type IntSliceOpt

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

IntSliceOpt modifies IntSlice variable configuration.

func IntSliceBase

func IntSliceBase(base int) IntSliceOpt

IntSliceBase specifies the base to use for a IntSlice variable.

func IntSliceBitSize

func IntSliceBitSize(bitSize int) IntSliceOpt

IntSliceBitSize specifies the bit size to use for a IntSlice variable.

func IntSliceComma

func IntSliceComma(comma rune) IntSliceOpt

IntSliceComma specifies the comma to use for a IntSlice variable.

func IntSliceDefault

func IntSliceDefault(def []int64) IntSliceOpt

IntSliceDefault specifies a default value for a IntSlice variable.

type Option

type Option func(c *Cfg)

func EnvFunc

func EnvFunc(envFunc func(string) (string, bool)) Option

func ErrMaker

func ErrMaker(f func(errs []error) error) Option

func Panic

func Panic(b bool) Option

type StringOpt

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

StringOpt modifies String variable configuration.

func StringDefault

func StringDefault(def string) StringOpt

StringDefault specifies a default value for a String variable.

type StringSliceOpt

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

StringSliceOpt modifies StringSlice variable configuration.

func StringSliceComma

func StringSliceComma(comma rune) StringSliceOpt

StringSliceComma specifies the comma to use for a StringSlice variable.

func StringSliceDefault

func StringSliceDefault(def []string) StringSliceOpt

StringSliceDefault specifies a default value for a StringSlice variable.

type TimeOpt

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

TimeOpt modifies Time variable configuration.

func TimeDefault

func TimeDefault(def time.Time) TimeOpt

TimeDefault specifies a default value for a Time variable.

func TimeLayout

func TimeLayout(layout string) TimeOpt

TimeLayout specifies the layout to use for a Time variable.

type UintOpt

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

UintOpt modifies Uint variable configuration.

func UintBase

func UintBase(base int) UintOpt

UintBase specifies the base to use for a Uint variable.

func UintBitSize

func UintBitSize(bitSize int) UintOpt

UintBitSize specifies the bit size to use for a Uint variable.

func UintDefault

func UintDefault(def uint64) UintOpt

UintDefault specifies a default value for a Uint variable.

type UniOpt

type UniOpt interface {
	// contains filtered or unexported methods
}
var Optional UniOpt = uniOptFunc(func(s *spec) {
	s.flags |= flagOptional
})

func Comment

func Comment(comment string) UniOpt

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

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