envar

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Feb 17, 2021 License: MIT Imports: 4 Imported by: 5

README

envar

GoDoc

This module simplifies use of environment variables in Go programs. The package was inspired by caarlos0/env and serves a similar purpose. This module is a lot smaller but also doesn't cover every use case.

The envar module supports only types string, all kinds of int type and also bool. I've never actually needed to export anything other than these so I decided to make a tiny module for my simple needs.

Example

A very basic example:

  1. Export environment variables: export THING1=living THING2=dying

  2. Run example and see a quote

package main

import (
	"fmt"

	"github.com/fabritsius/envar"
)

type config struct {
	Thing1 string `env:"THING1" default:"coding"`
	Thing2 string `env:"THING2" default:"eating"`
}

func main() {
	cfg := config{}
	// Populate config struct (pass a pointer)
	if err := envar.Fill(&cfg); err != nil {
		panic(err)
	}
	// Print a formatted quote
	fmt.Printf("\"Get busy %s or get busy %s.\" – Stephen King\n", cfg.Thing1, cfg.Thing2)
}

Result:

"Get busy living or get busy dying." – Stephen King

You can visit this gist to see another example.

Usage

  • pass a pointer of an empty struct to a function Fill()
  • each field in a struct can have two Tags env and default
  • use env to set a name of environment variable
  • use default to set a default value
  • each field must be of type string
  • each field is considered required (you can set empty default value)
  • error is returned when Fill() fails to fill a field

Examples of use can be found in envar_test.go file or on the GoDoc page.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Fill

func Fill(vars interface{}) error

Fill uses environment variables or defaults to assign values to element of a struct.

Example
package main

import (
	"fmt"
	"os"

	"github.com/fabritsius/envar"
)

func main() {
	// create couple environment variables
	createCoupleEnvs()

	type config struct {
		Name  string `env:"HERO"`
		Place string `env:"PLACE"`
	}

	cfg := config{}
	if err := envar.Fill(&cfg); err != nil {
		panic(err)
	}

	fmt.Printf("You gotta do it for Grandpa, %s. You gotta put these seeds inside your %s.\n", cfg.Name, cfg.Place)
}

func createCoupleEnvs() {
	os.Setenv("HERO", "Bob")
	os.Setenv("PLACE", "backpack")
}
Output:

You gotta do it for Grandpa, Bob. You gotta put these seeds inside your backpack.

Types

This section is empty.

Jump to

Keyboard shortcuts

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