A mapper of ENVironment variables to Structure for Go

envs .github/workflows/check.yml codecov

a mapper of ENVironment variables to a Structure for Go.

This library maps the environment variables to the struct according to the fields' types and tags.
Currently, it supports the following field types: string, int64, float64, bool, and the pointer for them.

Synopsis

Basic usage:

\"%s\"\n", e.Foo) fmt.Printf(" Bar => %d\n", e.Bar) fmt.Printf(" Buz => %f\n", e.Buz) fmt.Printf(" Qux => %v\n", e.Qux) fmt.Printf(" FooBar => \"%s\"\n", e.FooBar) fmt.Printf(" Nothing => \"%s\"\n", e.Nothing) // Output: // structured envvar: // Foo => "string-value" // Bar => 65535 // Buz => 123.456000 // Qux => true // FooBar => "" // Nothing => "" } ">
import (
	"fmt"
	"os"

	"github.com/moznion/envs"
)

type StructuredEnv struct {
	Foo     string  `envs:"FOO"`
	Bar     int64   `envs:"BAR"`
	Buz     float64 `envs:"BUZ"`
	Qux     bool    `envs:"QUX"`
	FooBar  string  `envs:"FOOBAR,allowempty"`
	Nothing string
}

func main() {
	_ = os.Setenv("FOO", "string-value")
	_ = os.Setenv("BAR", "65535")
	_ = os.Setenv("BUZ", "123.456")
	_ = os.Setenv("QUX", "true")

	var e StructuredEnv
	err := envs.Unmarshal(&e)
	if err != nil {
		panic(err)
	}
	fmt.Printf("structured envvar:\n")
	fmt.Printf("    Foo     => \"%s\"\n", e.Foo)
	fmt.Printf("    Bar     => %d\n", e.Bar)
	fmt.Printf("    Buz     => %f\n", e.Buz)
	fmt.Printf("    Qux     => %v\n", e.Qux)
	fmt.Printf("    FooBar  => \"%s\"\n", e.FooBar)
	fmt.Printf("    Nothing => \"%s\"\n", e.Nothing)

	// Output:
	// structured envvar:
	//     Foo     => "string-value"
	//     Bar     => 65535
	//     Buz     => 123.456000
	//     Qux     => true
	//     FooBar  => ""
	//     Nothing => ""
}

Pointer based usage:

\"%s\"\n", *pe.Foo) fmt.Printf(" Bar => %d\n", *pe.Bar) fmt.Printf(" Buz => %f\n", *pe.Buz) fmt.Printf(" Qux => %v\n", *pe.Qux) fmt.Printf(" FooBar => %v\n", pe.FooBar) fmt.Printf(" Nothing => %v\n", pe.Nothing) // Output: // pointer based structured envvar: // Foo => "string-value" // Bar => 65535 // Buz => 123.456000 // Qux => true // FooBar => // Nothing => } ">
import (
	"fmt"
	"os"

	"github.com/moznion/envs"
)

type PtrStructuredEnv struct {
	Foo     *string  `envs:"FOO"`
	Bar     *int64   `envs:"BAR"`
	Buz     *float64 `envs:"BUZ"`
	Qux     *bool    `envs:"QUX"`
	FooBar  *string  `envs:"FOOBAR,allowempty"`
	Nothing *string
}

func main() {
	_ = os.Setenv("FOO", "string-value")
	_ = os.Setenv("BAR", "65535")
	_ = os.Setenv("BUZ", "123.456")
	_ = os.Setenv("QUX", "true")

	var pe PtrStructuredEnv
	err = envs.Unmarshal(&pe)
	if err != nil {
		panic(err)
	}
	fmt.Printf("pointer based structured envvar:\n")
	fmt.Printf("    Foo     => \"%s\"\n", *pe.Foo)
	fmt.Printf("    Bar     => %d\n", *pe.Bar)
	fmt.Printf("    Buz     => %f\n", *pe.Buz)
	fmt.Printf("    Qux     => %v\n", *pe.Qux)
	fmt.Printf("    FooBar  => %v\n", pe.FooBar)
	fmt.Printf("    Nothing => %v\n", pe.Nothing)

	// Output:
	// pointer based structured envvar:
	//     Foo     => "string-value"
	//     Bar     => 65535
	//     Buz     => 123.456000
	//     Qux     => true
	//     FooBar  => 
     
	//     Nothing => 
     
}

and examples are here

Documentations

GoDoc

Author

moznion ([email protected])

Owner
moznion
I usually don't read e-mail. If you want to tell me something (e.g. "response an issue just now!"), please send me a message through twitter:@moznion.
moznion
Similar Resources

Quickly read variables from environment files

go-quick-env Quickly read variables from environment files The best way to import environment variables to your code, is by using .env files. This lib

May 11, 2021

Read files into environment variables and execute command

read-file-to-env -- Read files into environment variables and execute command Example use: read-file-to-env -one-line=HOST=/etc/hostname sh -c 'echo h

Nov 12, 2021

Golang library for reading properties from configuration files in JSON and YAML format or from environment variables.

go-config Golang library for reading properties from configuration files in JSON and YAML format or from environment variables. Usage Create config in

Aug 22, 2022

Environment variables configuration package for Go microservices.

gocfg Environment variables configuration package for Go microservices. It helps validate environment variable values and set default values if needed

Dec 30, 2021

formicidate is a small tool for Go application can update the value of environment variables in a .env file with code

formicidae Update .env files in Go with code. What is fomicidae? formicidate is a small tool for Go application. You can update the value of environme

Jan 23, 2022

Lightweight package that makes easier and safer to deal with environment variables.

Envisage A lightweight package that makes easier and safer to deal with environment variables. Example Try it on On GoPlay https://goplay.tools/snippe

Apr 11, 2022

Tmpl - A tool to apply variables from cli, env, JSON/TOML/YAML files to templates

tmpl allows to apply variables from JSON/TOML/YAML files, environment variables or CLI arguments to template files using Golang text/template and functions from the Sprig project.

Nov 14, 2022

✨Clean and minimalistic environment configuration reader for Golang

Clean Env Minimalistic configuration reader Overview This is a simple configuration reading tool. It just does the following: reads and parses configu

Jan 8, 2023

Golang Configuration tool that support YAML, JSON, TOML, Shell Environment

Configor Golang Configuration tool that support YAML, JSON, TOML, Shell Environment (Supports Go 1.10+) Usage package main import ( "fmt" "github.c

Dec 29, 2022
Comments
  • Configure Renovate

    Configure Renovate

    WhiteSource Renovate

    Welcome to Renovate! This is an onboarding PR to help you understand and configure settings before regular Pull Requests begin.

    🚦 To activate Renovate, merge this Pull Request. To disable Renovate, simply close this Pull Request unmerged.


    Detected Package Files

    • go.mod (gomod)

    Configuration Summary

    Based on the default config's presets, Renovate will:

    • Start dependency updates only once this onboarding PR is merged
    • Enable Renovate Dependency Dashboard creation
    • If semantic commits detected, use semantic commit type fix for dependencies and chore for all others
    • Ignore node_modules, bower_components, vendor and various test/tests directories
    • Autodetect whether to pin dependencies or maintain ranges
    • Rate limit PR creation to a maximum of two per hour
    • Limit to maximum 20 open PRs at any time
    • Group known monorepo packages together
    • Use curated list of recommended non-monorepo package groupings
    • Fix some problems with very old Maven commons versions
    • Ignore spring cloud 1.x releases
    • Ignore http4s digest-based 1.x milestones
    • Use node versioning for @types/node
    • Limit concurrent requests to reduce load on Repology servers until we can fix this properly, see issue 10133

    πŸ”‘ Would you like to change the way Renovate is upgrading your dependencies? Simply edit the renovate.json in this branch with your custom config and the list of Pull Requests in the "What to Expect" section below will be updated the next time Renovate runs.


    What to Expect

    It looks like your repository dependencies are already up-to-date and no Pull Requests will be necessary right away.


    ❓ Got questions? Check out Renovate's Docs, particularly the Getting Started section. If you need any further assistance then you can also request help here.


    This PR has been generated by WhiteSource Renovate. View repository job log here.

  • Update module go to 1.19

    Update module go to 1.19

    Mend Renovate

    This PR contains the following updates:

    | Package | Type | Update | Change | |---|---|---|---| | go (source) | golang | minor | 1.17 -> 1.19 |


    Release Notes

    golang/go

    v1.19.3

    v1.19.2

    v1.19.1

    v1.19.0

    v1.18.8

    v1.18.7

    v1.18.6

    v1.18.5

    v1.18.4

    v1.18.3

    v1.18.2

    v1.18.1

    v1.18.0


    Configuration

    πŸ“… Schedule: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

    🚦 Automerge: Disabled by config. Please merge this manually once you are satisfied.

    β™» Rebasing: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

    πŸ”• Ignore: Close this PR and you won't be reminded about this update again.


    • [ ] If you want to rebase/retry this PR, check this box

    This PR has been generated by Mend Renovate. View repository job log here.

  • Update module github.com/stretchr/testify to v1.8.1

    Update module github.com/stretchr/testify to v1.8.1

    Mend Renovate

    This PR contains the following updates:

    | Package | Type | Update | Change | |---|---|---|---| | github.com/stretchr/testify | require | minor | v1.7.0 -> v1.8.1 |


    Release Notes

    stretchr/testify

    v1.8.1

    Compare Source

    v1.8.0

    Compare Source

    v1.7.5

    Compare Source

    v1.7.4

    Compare Source

    v1.7.3

    Compare Source

    v1.7.2

    Compare Source

    v1.7.1

    Compare Source


    Configuration

    πŸ“… Schedule: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

    🚦 Automerge: Disabled by config. Please merge this manually once you are satisfied.

    β™» Rebasing: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

    πŸ”• Ignore: Close this PR and you won't be reminded about this update again.


    • [ ] If you want to rebase/retry this PR, check this box

    This PR has been generated by Mend Renovate. View repository job log here.

  • Dependency Dashboard

    Dependency Dashboard

    This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

    Other Branches

    These updates are pending. To force PRs open, click the checkbox below.

    • [ ] Update actions/checkout action to v3
    • [ ] Update actions/setup-go action to v3
    • [ ] Update codecov/codecov-action action to v3

    Open

    These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

    Detected dependencies

    github-actions
    .github/workflows/check.yml
    • actions/setup-go v2
    • actions/checkout v2
    • codecov/codecov-action v2
    gomod
    go.mod
    • go 1.17
    • github.com/stretchr/testify v1.7.0

    • [ ] Check this box to trigger a request for Renovate to run again on this repository
Simple lib to parse environment variables to structs

env Simple lib to parse envs to structs in Go. Example A very basic example: package main import ( "fmt" "time" // if using go modules "github.c

Jan 9, 2023
Un-marshaling environment variables to Go structs

envcfg Un-marshaling environment variables to Go structs Getting Started Let's set a bunch of environment variables and then run your go app #!/usr/bi

Sep 26, 2022
Small library to read your configuration from environment variables

envconfig envconfig is a library which allows you to parse your configuration from environment variables and fill an arbitrary struct. See the example

Nov 3, 2022
Go helpers to manage environment variables

Envh This library is made up of two parts : Env object : it wraps your environments variables in an object and provides convenient helpers. Env tree o

Sep 26, 2022
goconfig uses a struct as input and populates the fields of this struct with parameters from command line, environment variables and configuration file.

goconfig goconfig uses a struct as input and populates the fields of this struct with parameters from command line, environment variables and configur

Dec 15, 2022
A Go port of Ruby's dotenv library (Loads environment variables from `.env`.)

GoDotEnv A Go (golang) port of the Ruby dotenv project (which loads env vars from a .env file) From the original Library: Storing configuration in the

Jan 5, 2023
πŸ›  A configuration library for Go that parses environment variables, JSON files, and reloads automatically on SIGHUP
πŸ›  A configuration library for Go that parses environment variables, JSON files, and reloads automatically on SIGHUP

config A small configuration library for Go that parses environment variables, JSON files, and reloads automatically on SIGHUP. Example func main() {

Dec 11, 2022
Golang library for managing configuration data from environment variables

envconfig import "github.com/kelseyhightower/envconfig" Documentation See godoc Usage Set some environment variables: export MYAPP_DEBUG=false export

Dec 26, 2022
A Go library for parsing struct tags from environment variables.

Envconfig Envconfig populates struct field values based on environment variables or arbitrary lookup functions. It supports pre-setting mutations, whi

Jan 2, 2023
Environment variables substitution for Go

envsubst Environment variables substitution for Go. see docs below Installation: From binaries Latest stable envsubst prebuilt binaries for 64-bit Lin

Jan 1, 2023