env

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Apr 22, 2019 License: MIT Imports: 7 Imported by: 0

README

ENV - Lightweight Environment Variables Parser

Author's POV

Parses environmental variables to a struct using the struct field's env tag.

Usage


func main() {
  config := struct {
      // note the tag we are using
      // env determines what ENV var the *Parse func will be reading
      // envDefault sets the default value if ENV var is blank or not set
      Foo string `env:"FOO" envDefault:"BooHoo"`
  }

  os.Setenv("FOO", "Hoho")
  env.Parse(&config)
}

Supported Data Types

When creating the struct with it's fields the only supported types for now are:

  1. string
  2. int
  3. bool

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")
	// 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)
)

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
package main

import (
	"fmt"
	"os"

	"github.com/magicalbanana/env"
)

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

{/tmp/fakehome 3000 false}

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.

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