-
Notifications
You must be signed in to change notification settings - Fork 9
/
env.go
71 lines (52 loc) · 988 Bytes
/
env.go
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
// Package env provides environment variables support for uconfig
package env
import (
"os"
"strings"
"github.com/omeid/uconfig/flat"
"github.com/omeid/uconfig/plugins"
)
const tag = "env"
func init() {
plugins.RegisterTag(tag)
}
// New returns an EnvSet.
func New() plugins.Plugin {
return &visitor{}
}
type visitor struct {
fields flat.Fields
}
func makeEnvName(name string) string {
name = strings.Replace(name, ".", "_", -1)
name = strings.ToUpper(name)
return name
}
func (v *visitor) Visit(f flat.Fields) error {
v.fields = f
for _, f := range v.fields {
name, ok := f.Tag(tag)
if !ok || name == "" {
name = makeEnvName(f.Name())
}
f.Meta()[tag] = name
}
return nil
}
func (v *visitor) Parse() error {
for _, f := range v.fields {
name, ok := f.Meta()[tag]
if !ok || name == "-" {
continue
}
value, ok := os.LookupEnv(name)
if !ok {
continue
}
err := f.Set(value)
if err != nil {
return err
}
}
return nil
}