eflag is a small wrapper around github.com/spf13/pflag that adds environment variable fallbacks for flags while keeping the normal pflag flag definition API.
It is aimed at small CLI tools that want:
- normal
pflagflag definitions - env bindings close to the flag declarations
- command-line flags to win over environment variables
- both error-returning and panic-on-error APIs
go get github.com/kloudyuk/eflagpackage main
import (
"fmt"
"github.com/kloudyuk/eflag"
)
func main() {
var debug bool
var addr string
var port int
fs := eflag.NewFlagSet()
fs.BoolVar(&debug, "debug", false, "Enable debug logging")
fs.StringVarP(&addr, "addr", "a", "", "Server address")
fs.MustBindEnv("addr", "APP_ADDR")
fs.IntVarP(&port, "port", "p", 8080, "Server port")
fs.MustBindEnv("port", "APP_PORT")
fs.MustParse()
fmt.Println("debug:", debug)
fmt.Println("addr:", addr)
fmt.Println("port:", port)
}Help output includes the bound environment variables:
Usage of mytool:
--debug Enable debug logging
-a, --addr string Server address (env: APP_ADDR)
-p, --port int Server port (env: APP_PORT) (default 8080)
BindEnv("addr", "APP_ADDR")appends(env: APP_ADDR)to the flag usage text.- If a flag is set on the command line, that value wins.
- If a flag is not set on the command line and a bound environment variable is present, the environment variable is used.
Parse()returns an error.MustParse()panics on parse or env-binding errors, but exits cleanly on-hand--help.BindEnv()returns an error if the named flag does not exist.MustBindEnv()panics if the named flag does not exist.
Error-returning style:
fs := eflag.NewFlagSet()
if err := fs.BindEnv("addr", "APP_ADDR"); err != nil {
panic(err)
}
if err := fs.Parse(); err != nil {
panic(err)
}Convenience panic-on-error style:
fs := eflag.NewFlagSet()
fs.MustBindEnv("addr", "APP_ADDR")
fs.MustParse()eflagis designed for CLI entrypoints and parses fromos.Args[1:].eflag.FlagSetembedspflag.FlagSet, so normalpflagflag definition methods are available directly.
Use pflag if you just want flags and prefer to wire any environment variable handling yourself.
Use eflag if you regularly want:
- normal
pflagflag definitions - environment variable fallbacks with minimal setup
- help output that shows which environment variable is bound to a flag
- a small convenience layer for the common "flags plus env fallback" case
Tradeoffs to be aware of:
pflagis more established and lower-level.eflagis more opinionated and convenience-focused.eflagis intentionally small in scope and is not trying to replace fuller config systems.eflagis best suited to CLI entrypoints rather than general configuration frameworks.
Run:
go test ./...