-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
69 lines (62 loc) · 1.57 KB
/
config.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
package main
import (
"encoding/json"
"errors"
"io/ioutil"
"os"
"strconv"
"strings"
)
const (
envNamePort = "GOLOBA_PORT"
envNameTargets = "GOLOBA_TARGETS"
)
type config struct {
Port uint `json:"port"`
Servers []string `json:"servers"`
}
func loadConfig(fileName string) (config, error) {
envConfig, err := loadEnvs()
if err != nil {
return config{}, err
}
if envConfig.Port > 0 && len(envConfig.Servers) > 0 {
// necessary config given using environment variables
return envConfig, nil
}
// not all data given by environment variables - has to load file
var fileConfig config
confData, err := ioutil.ReadFile(fileName)
if err != nil {
return config{}, errors.New("Failed to open configuration file: " + fileName)
}
if err := json.Unmarshal(confData, &fileConfig); err != nil {
return config{}, errors.New("Failed to process configuration in file: " + err.Error())
}
if envConfig.Port > 0 {
fileConfig.Port = envConfig.Port
}
if len(envConfig.Servers) > 0 {
fileConfig.Servers = envConfig.Servers
}
return fileConfig, nil
}
func loadEnvs() (config, error) {
var result config
// ex. GOLOBA_PORT=8000
envPort := os.Getenv(envNamePort)
if len(envPort) > 0 {
val, err := strconv.ParseUint(envPort, 10, 32)
if err != nil {
return result, errors.New("Invalid PORT variable")
}
result.Port = uint(val)
}
// ex. GOLOBA_TARGETS="127.0.0.1:9000;10.0.0.1:9000"
envTargets := strings.Trim(os.Getenv(envNameTargets), "\"' \t")
if len(envTargets) > 0 {
parts := strings.Split(envTargets, ";")
result.Servers = parts
}
return result, nil
}