Go(lang) Environment Variable Parsing / Unmarshaler / Decoder

env

import "github.com/halorium/env"

Usage

Set some environment variables:

export TEST_STRING="some value"
export TEST_BOOL=true
export TEST_INT=1
export TEST_FLOAT=1.2
export TEST_DURATION="5s"
export TEST_LIST="one,two,three"
export TEST_MAP="one:1,two:2,three:3"

Write some code:

package main

import (
    "fmt"
    "log"
    "time"

    "github.com/halorium/env"
)

type Config struct {
	StringField   string         `env:"TEST_STRING"`
	BoolField     bool           `env:"TEST_BOOL"`
	IntField      int            `env:"TEST_INT"`
	FloatField    float64        `env:"TEST_FLOAT"`
	DurationField time.Duration  `env:"TEST_DURATION"`
	ListField     []string       `env:"TEST_LIST"`
	MapField      map[string]int `env:"TEST_MAP"`
}

func (c Config) String() string {
	val := fmt.Sprintf(
		"StringField:'%s'\nBoolField:'%v'\nIntField:'%d'\nFloatField:'%f'\nDurationField:'%s'\n",
		c.StringField,
		c.BoolField,
		c.IntField,
		c.FloatField,
		c.DurationField)

	val += "ListField:\n  " + strings.Join(c.ListField, "  \n") + "\n"

	val += "MapField:\n"
	for k, v := range c.MapField {
		val += fmt.Sprintf("  %s: %d\n", k, v)
	}

	return val
}

func main() {
	var cfg Config
	err := env.Unmarshal(&cfg)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(cfg)
}

Results:

 todo

Struct Tags

The default tag is 'env' however this can be changed in the options.

Example:

type Config struct {
	StringField   string         `custom:"TEST_STRING"`
	BoolField     bool           `custom:"TEST_BOOL"`
	IntField      int            `custom:"TEST_INT"`
	FloatField    float64        `custom:"TEST_FLOAT"`
	DurationField time.Duration  `custom:"TEST_DURATION"`
	ListField     []string       `custom:"TEST_LIST"`
	MapField      map[string]int `custom:"TEST_MAP"`
}

var cfg Config
options := env.Options{Tag: "custom"}
err := env.Unmarshal(&cfg, options)
if err != nil {
	log.Fatal(err)
}
fmt.Println(cfg)

Validation

env doesn't assume any validation, if an environment variable is not found then it is skipped.

The 'Required' option can be set to have an error returned if any environment variables are not set. Example:

var cfg Config
options := env.Options{Required: true}
err := env.Unmarshal(&cfg, options)
if err != nil {
	log.Fatal(err)
}
fmt.Println(cfg)

Ignored Fields

env will ignore the field if the tag is set to either an empty string '' or a hyphen '-'. Example:

type Config struct {
	StringField   string `env:"TEST_STRING"`
	BoolField     bool   `env:""`  // ignored
	IntField      int    `env:"-"` // ignored
}

Supported Field Types

  • string
  • int8, int16, int32, int64
  • bool
  • float32, float64
  • slices of any supported type
  • maps (keys and values of any supported type)
  • time.Duration

Note: Embedded structs using these fields are also supported.

Custom Unmarshaler

Any field whose type (or pointer-to-type) implements env.UnmarshalENV can control its own deserialization:

export IP=127.0.0.1
type CustomIP net.IP

func (c *CustomIP) UnmarshalENV(v string) error {
    *c = CustomIP(net.ParseIP(v))
    return nil
}

type Config struct {
    IP CustomIP `env:"IP"`
}

Other Ways to Use 'env'

env implements helper functions if you simply want to get environment variables as a specified type.

s, err := env.AsString("TEST_STRING") // returns (string, error)

b, err := env.AsBool("TEST_BOOL") // returns (bool, error)

i, err := env.AsInt("TEST_INT", 64) // returns (int64, error)

i, err := env.AsUint("TEST_UINT", 64) // returns (uint64, error)

f, err := env.AsFloat("TEST_FLOAT", 64) // returns (float64, error)

d, err := env.AsDuration("TEST_DURATION") // returns (time.Duration, error)
Similar Resources

Sample multi docker compose environment setup

Instructions This is a demonstration of a Multi Docker Compose. The purpose of this repositoy is ongoing research on "Docker compose" architecture des

Oct 21, 2022

Stackie enables developers to configure their local environment/toolchain with ease.

Stackie enables developers to configure their local environment/toolchain with ease. Made for Pulumi CLI, Google Cloud Platform (gcloud), and Amazon Web Services (aws-cli).

Sep 10, 2021

fiber-air-docker development environment boilerplate, examples

fiber-air-docker development environment boilerplate, examples

ON AIR! fiber-air-docker development environment boilerplate TODO on air 세션 준비 fiber 유저 준비 gorm 외래키 준비 아키텍쳐 참고 https://blog.puppyloper.com/menus/Golan

Sep 14, 2022

Go Trusted Execution Environment (TEE)

Go Trusted Execution Environment (TEE)

Introduction The GoTEE framework implements concurrent instantiation of TamaGo based unikernels in privileged and unprivileged modes, interacting with

Dec 5, 2022

Interactive Cloud-Native Environment Client

Interactive Cloud-Native Environment Client

Fenix-CLI:Interactive Cloud-Native Environment Client English | 简体中文 Fenix-CLI is an interactive cloud-native operating environment client. The goal i

Dec 15, 2022

A penetration toolkit for container environment

ctrsploit: A penetration toolkit for container environment 中文文档 Pre-Built Release https://github.com/ctrsploit/ctrsploit/releases Usage Quick-Start wg

Dec 6, 2022

The OCI Service Operator for Kubernetes (OSOK) makes it easy to connect and manage OCI services from a cloud native application running in a Kubernetes environment.

OCI Service Operator for Kubernetes Introduction The OCI Service Operator for Kubernetes (OSOK) makes it easy to create, manage, and connect to Oracle

Sep 27, 2022

Environment-driven Docker credential helper

Docker Credentials from the Environment A docker credential helper to streamline repository interactions in CI/CD pipelines, particularly Jenkins decl

Jul 13, 2022

Development environment for golang

docker-go-sample Development environment for golang Build docker-compose up -d -

Dec 17, 2021
Related tags
Go lang IDE. Built with GopherSauce
Go lang IDE. Built with GopherSauce

IDE runs as a server and is accessed via web browser. Being a web server, the IDE boasts a web (HTML) interface is accessible from any device on your network.Compared to Microsoft VS Code and Eclipse CHE, this IDE is very minimalistic

Nov 28, 2022
Simple example using Git actions + Argo CD + K8S + Docker and GO lang

CICD-simple_example Simple example using Git actions + Argo CD + K8S + Docker and GO lang Intro Pre reqs Have an ArgoCD account and Installed. Docker

Oct 28, 2021
A Simple to use golang masking tool to mask sensitive information from go-lang data-structures

Golang Masking Tool Golang Masking Tool is a simple utility of creating a masker tool which you can use to mask sensitive information. You can use a v

Dec 1, 2022
Progress OpenEdge Profiler data parsing to OpenTracing format

openedge-profiler-parser Progress OpenEdge Profiler data parsing to OpenTracing format. Prerequisites In order to RUN you will be enough with Docker:

Nov 9, 2021
AWS environment config loader

awsenv AWS environment config loader. awsenv is a small binary that loads AWS environment variables for an AWS profile from ~/.aws/credentials - usefu

Nov 28, 2022
A multi-service dev environment for teams on Kubernetes
A multi-service dev environment for teams on Kubernetes

Tilt Kubernetes for Prod, Tilt for Dev Modern apps are made of too many services. They're everywhere and in constant communication. Tilt powers multi-

Jan 5, 2023
:recycle: Now you can easily rollback to previous deployed images whatever you want on k8s environment

EasyRollback EasyRollback is aim to easy rollback to previous images that deployed on k8s environment Installation You should have go installation fir

Dec 24, 2022
Open URL in your local web browser from the SSH-connected remote environment.

opener Open URL in your local web browser from the SSH-connected remote environment. How does opener work? opener is a daemon process that runs locall

Oct 20, 2022
A tool to build, deploy, and release any environment using System Containers.
A tool to build, deploy, and release any environment using System Containers.

Bravetools Bravetools is an end-to-end System Container management utility. Bravetools makes it easy to configure, build, and deploy reproducible envi

Dec 14, 2022
Testcontainers is a Golang library that providing a friendly API to run Docker container. It is designed to create runtime environment to use during your automatic tests.

When I was working on a Zipkin PR I discovered a nice Java library called Testcontainers. It provides an easy and clean API over the go docker sdk to

Jan 7, 2023