forked from Nomon/gonfig
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathenv.go
43 lines (39 loc) · 1.14 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
package unicon
import (
"os"
"strings"
)
// EnvConfig can be used to read values from the environment
// into the underlaying Configurable
type EnvConfig struct {
Configurable
Prefix string
namespaces []string
}
// NewEnvConfig creates a new Env config backed by a memory config
func NewEnvConfig(prefix string, namespaces ...string) ReadableConfig {
cfg := &EnvConfig{
Configurable: NewMemoryConfig(),
Prefix: prefix,
namespaces: nsSlice(namespaces),
}
cfg.Load()
return cfg
}
// Load loads the data from os.Environ() to the underlaying Configurable.
// if a Prefix is set then variables are imported with self.Prefix removed from the name
// so MYAPP_test=1 exported in env and read from ENV by EnvConfig{Prefix:"MYAPP_"} can be found from
// EnvConfig.Get("test")
// If namespaces are declared, POSTGRESQL_HOST becomes postgresql.host
func (ec *EnvConfig) Load() (err error) {
env := os.Environ()
for _, pair := range env {
kv := strings.Split(pair, "=")
if kv != nil && len(kv) >= 2 {
name := strings.Replace(kv[0], ec.Prefix, "", 1)
name = namespaceKey(name, ec.namespaces)
ec.Set(name, kv[1])
}
}
return nil
}