forked from RichardKnop/machinery
-
Notifications
You must be signed in to change notification settings - Fork 0
/
file.go
92 lines (73 loc) · 1.82 KB
/
file.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package config
import (
"fmt"
"os"
"time"
"github.com/RichardKnop/machinery/v1/log"
"gopkg.in/yaml.v2"
)
// NewFromYaml creates a config object from YAML file
func NewFromYaml(cnfPath string, mustLoadOnce, keepReloading bool) *Config {
if configLoaded {
return cnf
}
// If the config must be loaded once successfully
if mustLoadOnce && !configLoaded {
newCnf, err := fromFile(cnfPath)
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 file for the first time")
}
if keepReloading {
// Open a goroutine to watch remote changes forever
go func(theConfigPath string) {
for {
// Delay after each request
<-time.After(reloadDelay)
// Attempt to reload the config
newCnf, err := fromFile(theConfigPath)
if err != nil {
log.WARNING.Print("Failed to reload config from file: ", err)
continue
}
// Refresh the config
Refresh(newCnf)
// Set configLoaded to true
configLoaded = true
}
}(cnfPath)
}
return cnf
}
// ReadFromFile reads data from a file
func ReadFromFile(cnfPath string) ([]byte, error) {
file, err := os.Open(cnfPath)
// Config file not found
if err != nil {
return nil, fmt.Errorf("Open file error: %s", err)
}
// Config file found, let's try to read it
data := make([]byte, 1000)
count, err := file.Read(data)
if err != nil {
return nil, fmt.Errorf("Read from file error: %s", err)
}
return data[:count], nil
}
func fromFile(cnfPath string) (*Config, error) {
var newCnf Config
newCnf = *cnf
data, err := ReadFromFile(cnfPath)
if err != nil {
return nil, err
}
if err := yaml.Unmarshal(data, &newCnf); err != nil {
return nil, fmt.Errorf("Unmarshal YAML error: %s", err)
}
return &newCnf, nil
}