Skip to content
/ env Public

Package env reads and parses environment variables from various sources.

License

Notifications You must be signed in to change notification settings

go-pogo/env

Repository files navigation

env

Latest release Build status Go Report Card Documentation

Package env reads and parses environment variables from various sources. It supports unmarshaling into any type and (over)loading the variables into the system's environment.

Included features are:

  • Reading environment variables from various sources;
  • Decoding environment variables into any type;
  • Encoding environment variables from any type;
  • Loading and overloading into the system's environment variables.

go get github.com/go-pogo/env
import "github.com/go-pogo/env"

Usage

Below example demonstrates how to decode system environment variables into a struct.

package main

import (
    "github.com/davecgh/go-spew/spew"
    "github.com/go-pogo/env"
    "time"
)

func main() {
    type Config struct {
        Foo     string
        Timeout time.Duration `default:"10s"`
    }

    var conf Config
    if err := env.NewDecoder(env.System()).Decode(&conf); err != nil {
        panic(err)
    }

    spew.Dump(conf)
    // Output:
    // (env.Config) {
    //  Foo: (string) "",
    //  Timeout: (time.Duration) 10s
    // }
}

Usage with dotenv

This example reads .env files from the example directory and decodes the found variables into a struct.

package main

import (
    "github.com/davecgh/go-spew/spew"
    "github.com/go-pogo/env"
    "github.com/go-pogo/env/dotenv"
    "time"
)

func main() {
    type Config struct {
        Foo     string
        Timeout time.Duration `default:"10s"`
    }

    var conf Config
    if err := env.NewDecoder(dotenv.Read("example", dotenv.None)).Decode(&conf); err != nil {
        panic(err)
    }

    spew.Dump(conf)
    // Output:
    // (dotenv.Config) {
    //  Foo: (string) (len=3) "bar",
    //  Timeout: (time.Duration) 2s
    // }
}

Documentation

Additional detailed documentation is available at pkg.go.dev

Created with

License

Copyright © 2020-2024 Roel Schut. All rights reserved.

This project is governed by a BSD-style license that can be found in the LICENSE file.