forked from RichardKnop/machinery
/
env.go
66 lines (52 loc) · 1.27 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
package config
import (
"time"
"github.com/GetStream/machinery/v1/log"
"github.com/kelseyhightower/envconfig"
)
// NewFromEnvironment creates a config object from environment variables
func NewFromEnvironment(mustLoadOnce, keepReloading bool) *Config {
if configLoaded {
return cnf
}
// If the config must be loaded once successfully
if mustLoadOnce && !configLoaded {
newCnf, err := fromEnvironment()
if err != nil {
log.FATAL.Fatal(err)
}
// Refresh the config
Refresh(newCnf)
// Set configLoaded to true
configLoaded = true
log.INFO.Print("Successfully loaded config from environment for the first time")
}
if keepReloading {
// Open a goroutine to watch remote changes forever
go func() {
for {
// Delay after each request
<-time.After(reloadDelay)
// Attempt to reload the config
newCnf, err := fromEnvironment()
if err != nil {
log.WARNING.Print("Failed to reload config from environment: ", err)
continue
}
// Refresh the config
Refresh(newCnf)
// Set configLoaded to true
configLoaded = true
}
}()
}
return cnf
}
func fromEnvironment() (*Config, error) {
var newCnf Config
newCnf = *cnf
if err := envconfig.Process("", &newCnf); err != nil {
return nil, err
}
return &newCnf, nil
}