-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathconfig.go
93 lines (77 loc) · 1.61 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package main
import (
"fmt"
"strings"
"io/ioutil"
"gopkg.in/yaml.v2"
)
const configName string = "config.yml"
func validation(condition bool, errorMessage string) string {
if condition {
return errorMessage
} else {
return ""
}
}
func removeEmpty(errors []string) []string {
var filtered = []string{}
for _,e := range errors {
if e != "" {
filtered = append(filtered, e)
}
}
return filtered
}
func generateValidationErrors(proxy Proxy) []string {
return removeEmpty([]string{
validation(
proxy.Host == "",
"the 'host' field cannot be blank",
),
validation(
proxy.Port == 0,
"the 'port' field cannot be blank",
),
validation(
len(proxy.Servers) == 0,
"the config must specify at least 1 server",
),
validation(
proxy.Scheme != "http" && proxy.Scheme != "https",
"the proxy scheme must be either 'http' or 'https'",
),
})
}
func validateFields(proxy Proxy) error {
var errors = generateValidationErrors(proxy)
if(len(errors) == 0) {
return nil
} else {
return fmt.Errorf(strings.Join(errors, ", "))
}
}
func setDefaultValues(proxy *Proxy) {
if proxy.Port == 0 {
proxy.Port = 80
}
if proxy.Scheme == "" {
proxy.Scheme = "http"
}
}
func ReadConfig() (Proxy, error) {
proxy := Proxy{}
file, err := ioutil.ReadFile(configName)
if err != nil {
return proxy, err
}
err = yaml.Unmarshal(file, &proxy)
if err != nil {
return proxy, err
}
setDefaultValues(&proxy)
err = validateFields(proxy)
if err != nil {
return proxy, err
}
return proxy, nil
}