-
Notifications
You must be signed in to change notification settings - Fork 13
/
env.go
74 lines (63 loc) · 1.91 KB
/
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
72
73
74
// Copyright (c) 2017 Steven Roose <[email protected]>.
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
package gonfig
import (
"fmt"
"os"
"strings"
)
// makeEnvKey creates the environment variable key with the opts fullId and
// prefix by joining all parts together with underscores and putting all to
// upper case.
func makeEnvKey(prefix string, fullID []string) string {
key := strings.Join(fullID, "_")
key = strings.Replace(key, "-", "_", -1)
key = prefix + key
key = strings.ToUpper(key)
return key
}
// parseEnv parses the environment variables for all config options
// and writes the values that have been found in place.
func parseEnv(s *setup) error {
for _, opt := range s.allOpts {
if opt.isParent {
continue
}
envKey := makeEnvKey(s.conf.EnvPrefix, opt.fullIDParts)
if opt.isMap {
// An exception for maps, we need to look for all prefixed vars.
pref := envKey + "_"
for _, env := range os.Environ() {
split := strings.SplitN(env, "=", 2)
key, value := split[0], split[1]
if strings.HasPrefix(key, pref) {
mapKey := strings.ToLower(strings.TrimPrefix(key, pref))
if err := setSimpleMapValue(opt.value, mapKey, value); err != nil {
return fmt.Errorf(
"error parsing map value '%v' for config var %v: %v",
value, opt.fullID(), err)
}
}
}
continue
}
value, set := os.LookupEnv(envKey)
if !set {
continue
}
if err := setValueByString(opt.value, value); err != nil {
return fmt.Errorf("failed to set option '%v' with value '%v': %v",
opt.fullID(), value, err)
}
}
return nil
}
// lookupConfigFileEnv looks for the config file in the environment variables.
func lookupConfigFileEnv(s *setup, configOpt *option) (string, error) {
val, found := os.LookupEnv(makeEnvKey(s.conf.EnvPrefix, configOpt.fullIDParts))
if !found {
return "", nil
}
return val, nil
}