-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrawenv.go
60 lines (52 loc) · 1.5 KB
/
rawenv.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
package envcnf
import (
"os"
"strings"
)
// rawEnv is used to obtain and handle sets of environment variables.
type rawEnv map[string]string
// newRawEnv obtains all environment variables with the given prefix via os.Environ,
// and packages those in a rawEnv map type.
// If prefix is the empty string,
// all variables defined in the processes's environment are being returned.
func newRawEnv(prefix string) rawEnv {
rawvals := os.Environ()
var env rawEnv
if prefix == "" {
env = make(rawEnv, len(rawvals))
} else {
env = make(rawEnv)
}
for _, rawval := range rawvals {
if !strings.HasPrefix(rawval, prefix) {
continue
}
keyval := strings.SplitN(rawval, "=", 2)
key := strings.TrimPrefix(keyval[0], prefix)
env[key] = keyval[1]
}
return env
}
// newRawEnvWithPrfxSep returns the full env if prefix is the empty string,
// otherwise the limited subset of env vars that begin with prefix+sepchar
// is selected and prefix+sepchar is stripped from the env var names.
func newRawEnvWithPrfxSep(prefix, sepchar string) rawEnv {
var env rawEnv
if prefix == "" {
env = newRawEnv(prefix)
} else {
env = newRawEnv(prefix + sepchar)
}
return env
}
// getAllWithPrefix returns the subset of values in the map that start with the
// given prefix, the prefix is stripped from the keys in the returned map.
func (r rawEnv) getAllWithPrefix(prefix string) rawEnv {
sub := make(rawEnv)
for k, v := range r {
if strings.HasPrefix(k, prefix) {
sub[strings.TrimPrefix(k, prefix)] = v
}
}
return sub
}