Skip to content

Golang library for managing configuration data from environment variables

License

Notifications You must be signed in to change notification settings

adrianduke/envconfig

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

31 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

envconfig

Build Status

import "github.com/kelseyhightower/envconfig"

Documentation

See godoc

Usage

Set some environment variables:

export MYAPP_DEBUG=false
export MYAPP_PORT=8080
export MYAPP_USER=Kelsey
export MYAPP_RATE="0.5"

Write some code:

package main

import (
    "fmt"
    "log"

    "github.com/kelseyhightower/envconfig"
)

type Specification struct {
    Debug bool
    Port  int
    User  string
    Rate  float32
}

func main() {
    var s Specification
    err := envconfig.Process("myapp", &s)
    if err != nil {
        log.Fatal(err.Error())
    }
    format := "Debug: %v\nPort: %d\nUser: %s\nRate: %f\n"
    _, err = fmt.Printf(format, s.Debug, s.Port, s.User, s.Rate)
    if err != nil {
        log.Fatal(err.Error())
    }
}

Results:

Debug: false
Port: 8080
User: Kelsey
Rate: 0.500000

Register and use custom decoders:

export MYAPP_KEYS=key1,key2,key3
package main

import (
    "fmt"
    "log"
    "reflect"
    "strings"

    "github.com/kelseyhightower/envconfig"
)

type Specification struct {
    Keys []string
}

func main() {
    var s Specification
    envconfig.RegisterDecoder("Keys", func(value string, fieldValue, struc reflect.Value) error {
        items := strings.Split(value, ",")
        n := len(items)

        if fieldValue.Len() < n {
            fieldValue.Set(reflect.MakeSlice(fieldValue.Type(), n, n))
        }

        for i, v := range items {
            fieldValue.Index(i).SetString(v)
        }

        return nil
    })
    defer envconfig.ClearDecoders()
    err := envconfig.Process("myapp", &s)
    if err != nil {
        log.Fatal(err.Error())
    }
    format := "Keys: %v"
    _, err = fmt.Printf(format, s.Keys)
    if err != nil {
        log.Fatal(err.Error())
    }
}
Keys: [key1  key2  key3]

Struct Tag Support

Envconfig supports the use of struct tags to specify alternate environment variables.

For example, consider the following struct:

type Specification struct {
    MultiWordVar `envconfig:"multi_word_var"`
}

Whereas before, the value for MultiWordVar would have been populated with MYAPP_MULTIWORDVAR, it will now be populated with MYAPP_MULTI_WORD_VAR.

export MYAPP_MULTI_WORD_VAR="this will be the value"

# export MYAPP_MULTIWORDVAR="and this will not"

About

Golang library for managing configuration data from environment variables

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Go 100.0%