ucarion / envflag

Archived in favor of github.com/ucarion/conf

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

envflag godoc ci

envflag is a Golang package that enhances the standard library's flag package with the ability to read from environment variables. Just change:

flag.Parse()

To:

envflag.Parse()

And you'll get env variable goodness. No further changes required.

Installation

You can add this package using go get as follows:

go get github.com/ucarion/envflag

Example

Here is your typical example usage of flag:

package main

import (
  "flag"
  "fmt"
)

func main() {
  foo := flag.String("foo", "asdf", "some string param")
  bar := flag.Int("bar", 123, "some int param")

  flag.Parse()

  fmt.Println("foo", *foo)
  fmt.Println("bar", *bar)
}

Here is how you convert that into also using envflag:

package main

import (
  "flag"
  "fmt"

  "github.com/ucarion/envflag"
)

func main() {
  foo := flag.String("foo", "asdf", "some string param")
  bar := flag.Int("bar", 123, "some int param")

  envflag.Parse()

  fmt.Println("foo", *foo)
  fmt.Println("bar", *bar)
}

Assuming you put this in a file called ./examples/simple/main.go (like the one you can find in this repo), you can invoke it as so:

$ go run ./examples/simple/...
foo asdf
bar 123

$ SIMPLE_FOO=from-env go run ./examples/simple/...
foo from-env
bar 123

$ SIMPLE_FOO=from-env go run ./examples/simple/... --foo=from-args
foo from-args
bar 123

$ SIMPLE_FOO=from-env SIMPLE_BAR=456 go run ./examples/simple/...
foo from-env
bar 456

The env variables are prefixed with SIMPLE_, because that's the basename of os.Args[0]. Prefixing env variables like this helps you keep your config separate from others.

If you would prefer to disable this prefixing, instead of doing:

envflag.Parse()

Do:

// The first parameter to Load is a prefix for all env variables. The empty
// string disables prefixing env variables.
//
// Unlike envflag.Parse, envflag.Load does not call flag.Parse() for
// you. So you'll need to call flag.Parse() yourself.
envflag.Load("", flag.CommandLine)
flag.Parse()

About

Archived in favor of github.com/ucarion/conf

License:MIT License


Languages

Language:Go 100.0%