-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathenvflags.go
More file actions
51 lines (44 loc) · 1.09 KB
/
envflags.go
File metadata and controls
51 lines (44 loc) · 1.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/*
Package envflags exposes an enhanced flag.Flagset
which injects environment variables at the highest precedence.
see: https://golang.org/pkg/flag/
*/
package envflags
import (
"flag"
"os"
"strings"
)
// FlagSet is a flag.Flagset and exposes all normal Flagset methods.
//
// see: https://golang.org/pkg/flag/
type FlagSet struct {
flag.FlagSet
transform func(string) string
}
// New return a new *FlagSet
func New() *FlagSet {
return &FlagSet{
flag.FlagSet{},
strings.ToUpper,
}
}
// Transform apply a transformation to the flag name when searching the ENVIRONMENT
// Any func string -> string is suitable.
//
// default is https://golang.org/pkg/strings/#ToUpper
func (f *FlagSet) Transform(transform func(string) string) *FlagSet {
f.transform = transform
return f
}
// Parse flag.Parse and inject the environment at highest precedence.
func (f *FlagSet) Parse() {
// get command line stuff and defaults
f.FlagSet.Parse(os.Args[1:])
// inject environment
f.VisitAll(func(flag *flag.Flag) {
if value, OK := os.LookupEnv(f.transform(flag.Name)); OK {
flag.Value.Set(value)
}
})
}