jesper / envconfig

Golang library for managing configuration data from environment variables

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

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

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.

If envconfig can't find an environment variable in the form PREFIX_MYVAR, and there is a struct tag defined, it will try to populate your variable with an environment variable that directly matches the envconfig tag in your struct definition:

export SERVICE_HOST=127.0.0.1
export MYAPP_DEGUB=true
type Specification struct {
	ServiceHost	`envconfig:"SERVICE_HOST"`
	Debug bool
}
export MYAPP_MULTI_WORD_VAR="this will be the value"

# export MYAPP_MULTIWORDVAR="and this will not"

Envconfig also supports setting a struct tag to mark a field as required.

For example:

type Specification struct {
    Hello string `envconfig_required_field:"true"`
    Goodbye string
}

In this example, envconfig.process("app", &Specification{}) will return an error unless the environment variable "APP_HELLO" has been set.

About

Golang library for managing configuration data from environment variables

License:MIT License


Languages

Language:Go 100.0%