package module
v0.0.0-...-5b08454 Latest Latest

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

Go to latest
Published: Jun 18, 2024 License: MIT Imports: 6 Imported by: 66



Tag-based environment configuration for structs.

Godoc Build Status Go Report Card


$ go get -u github.com/codingconcepts/env


package main

import (


type config struct {
	Secret            []byte        `env:"SECRET" required:"true"`
	Region            string        `env:"REGION"`
	Port              int           `env:"PORT" required:"true"`
	Peers             []string      `env:"PEERS"` // you can use `delimiter` tag to specify separator, for example `delimiter:" "` 
	ConnectionTimeout time.Duration `env:"TIMEOUT" default:"10s"`

func main() {
	c := config{}
	if err := env.Set(&c); err != nil {

$ ID=1 SECRET=shh PORT=1234 PEERS=localhost:1235,localhost:1236 TIMEOUT=5s go run main.go

Supported field types

  • bool and []bool
  • string and []string
  • []byte
  • int, int8, int16, int32, int64, []int, []int8, []int16, []int32, and []int64
  • uint, uint8, uint16, uint32, uint64, []uint, []uint8, []uint16, []uint32, and []uint64
  • float32, float64, []float32, and []float64
  • time.Duration and []time.Duration



Package env makes satisfying factor III of the 12-factor methodology easy, by allowing struct fields to be populated directly from environment variables with the use of struct tags.

To use, create a struct tag called "env" and call env.Set, passing a pointer to the struct you wish to populate. You can optionally, provide a "required" tag to determine whether an error should be returned in the event of missing environment configuration.

Like the encoding/* packages, env.Set will return an error if a non-pointer type is provided.




This section is empty.


This section is empty.


func Set

func Set(i interface{}) (err error)

Set sets the fields of a struct from environment config. If a field is unexported or required configuration is not found, an error will be returned.

os.Setenv("HOSTS", "NEHOST1:1234, NEHOST2:1234")
os.Setenv("PORT", "1234")
os.Setenv("PEER_TIMEOUT", "2m500ms")

config := struct {
	Hosts              []string      `env:"HOSTS" required:"true"`
	Port               int16         `env:"PORT" required:"true"`
	PeerConnectTimeout time.Duration `env:"PEER_TIMEOUT" default:"1s500ms"`

err := Set(&config)

fmt.Println(config, err)

{[NEHOST1:1234 NEHOST2:1234] 1234 2m0.5s} <nil>

func SetPrefix

func SetPrefix(i interface{}, prefix string) (err error)

SetPrefix sets the fields of a struct from environment config with a given prefix. If a field is unexported or required configuration is not found, an error will be returned.


type Setter

type Setter interface {
	Set(string) error

Setter is called for any complex struct field with an implementation, allowing developers to override Set behaviour.

Jump to

Keyboard shortcuts

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