Skip to content

Simple and tiny library to load environment variables into a struct.

License

Notifications You must be signed in to change notification settings

byteartis/neoenv

Repository files navigation

Simple and tiny library to load environment variables into a struct.

neoenv

import "github.com/byteartis/neoenv"

Index

func Load

func Load[T any]() (*T, error)

Load reads the environment variables and populates the struct defined in T. T must be a struct otherwise it will thrown an error. Each nested level within the struct is sepearated by '__'.

Example

package main

import (
	"os"

	"github.com/byteartis/neoenv"
)

func main() {
	type Config struct {
		// When 'env' is omitted, the field name snake-cased is used as the key, e.g., 'newrelic_enabled'
		NewrelicEnabled bool
		// When 'env' is omitted, the field name snake-cased is used as the key, e.g., 'database'
		Database struct {
			// Nested properties are joined by '__', e.g., 'database__host'
			Host string `env:"host"`
			// Nested properties are joined by '__', e.g., 'database__host'
			Port uint `env:"port"`
		}
		Subscribers struct {
			// Nested properties are joined by '__', e.g., 'subscribers__order_management'
			OrderManagement string `env:"order_management"`
			// When 'env' is omitted, the field name snake-cased is used as the key, e.g., 'member_account'
			MemberAccount string
			// The 'env' tag can be set to any name without necessarily matching the field name in the structure
			Member string `env:"api_member"`
		} `env:"subscribers"`
		ListOfStrings []string  `env:"list_of_strings"`
		ListOfUInts   []uint    `env:"list_of_uints"`
		ListOfFloats  []float32 `env:"list_of_floats"`
	}

	os.Setenv("NEWRELIC_ENABLED", "true")
	os.Setenv("DATABASE__HOST", "localhost")
	os.Setenv("DATABASE__PORT", "5432")
	os.Setenv("SUBSCRIBERS__ORDER_MANAGEMENT", "subscriber_order_management")
	os.Setenv("SUBSCRIBERS__MEMBER_ACCOUNT", "subscriber_member_account")
	os.Setenv("SUBSCRIBERS__API_MEMBER", "subscriber_api_member")
	os.Setenv("LIST_OF_STRINGS", "one,two,three")
	os.Setenv("LIST_OF_UINTS", "1,2,3")
	os.Setenv("LIST_OF_FLOATS", "1.1,2.2,3.3")

	cfg, err := neoenv.Load[Config]()
	if err != nil {
		panic(err)
	}

	// Use the configuration
	_ = cfg
}

Generated by gomarkdoc

About

Simple and tiny library to load environment variables into a struct.

Topics

Resources

License

Stars

Watchers

Forks