Skip to content

ableinc/go-env

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

22 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Go env

A simple library to load environment variables from a file into your program at runtime. If the same key appears multiple times, the last occurrence wins. Inline comments (# ...) are stripped from unquoted values; quoted values ("..." or '...') are taken verbatim.

Install

go get github.com/ableinc/go-env

API

LoadEnv(filepath ...string)

Loads environment variables from a .env file into the process environment. Defaults to .env if no path is given.

import goenv "github.com/ableinc/go-env"

goenv.LoadEnv()                   // loads .env
goenv.LoadEnv(".env.development") // loads .env.development

Process(s any, filepath ...string) error

Loads a .env file (defaults to .env) and maps the resulting environment variables into a struct using struct tags.

type Config struct {
    Host         string        `envconfig:"DB_HOST"      required:"true"`
    Port         int           `envconfig:"DB_PORT"      default:"5432"`
    Password     string        `envconfig:"DB_PASS"`
    ReadTimeout  time.Duration `envconfig:"READ_TIMEOUT" default:"30s"`
    AppEnv       string        `split_words:"true"`  // maps to APP_ENV
    Internal     string        `ignored:"true"`
}

var cfg Config
if err := goenv.Process(&cfg); err != nil {
    log.Fatal(err)
}

// or with a custom file:
if err := goenv.Process(&cfg, ".env.development"); err != nil {
    log.Fatal(err)
}

Struct Tags

Tag Description
envconfig:"KEY" Env var name to look up. Required unless split_words is set.
split_words:"true" Derives the env key from the field name (CamelCaseUPPER_SNAKE_CASE). Ignored when envconfig is also set.
required:"true" Returns an error if the env var is unset and no default is provided.
default:"value" Fallback value when the env var is unset or empty.
ignored:"true" Skips the field entirely.

Supported field types: string, int/int8/int16/int32/int64, uint/uint8/uint16/uint32/uint64, float32/float64, bool, time.Duration.


Run Tests

make test

Build from Source

make build

About

Load environment variables into your project really fast

Topics

Resources

Stars

Watchers

Forks

Packages

 
 
 

Contributors