-
Notifications
You must be signed in to change notification settings - Fork 98
/
config.go
89 lines (79 loc) · 1.96 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
package main
import (
"encoding/json"
"flag"
"fmt"
"github.com/sirupsen/logrus"
"io/ioutil"
"regexp"
)
type configStructure struct {
LogLevel string `json:"log_level"`
Rules []*ruleStructure `json:"rules"`
}
type ruleStructure struct {
Name string `json:"name"`
Listen string `json:"listen"`
EnableRegexp bool `json:"enable_regexp"`
Targets []*struct {
Regexp string `json:"regexp"`
regexp *regexp.Regexp `json:"-"`
Address string `json:"address"`
} `json:"targets"`
FirstPacketTimeout uint64 `json:"first_packet_timeout"`
Blacklist map[string]bool `json:"blacklist"`
}
var config *configStructure
func init() {
cfgPath := flag.String("config", "config.json", "config.json file path")
flag.Parse()
buf, err := ioutil.ReadFile(*cfgPath)
if err != nil {
logrus.Fatalf("failed to load config json: %s", err.Error())
}
if err := json.Unmarshal(buf, &config); err != nil {
logrus.Fatalf("failed to load config json: %s", err.Error())
}
if len(config.Rules) == 0 {
logrus.Fatalf("empty rule")
}
lvl, err := logrus.ParseLevel(config.LogLevel)
if err != nil {
logrus.Fatalf("invalid log_level")
}
logrus.SetLevel(lvl)
for i, v := range config.Rules {
if err := v.verify(); err != nil {
logrus.Fatalf("verity rule failed at pos %d : %s", i, err.Error())
}
}
}
func (c *ruleStructure) verify() error {
if c.Name == "" {
return fmt.Errorf("empty name")
}
if c.Listen == "" {
return fmt.Errorf("invalid listen address")
}
if len(c.Targets) == 0 {
return fmt.Errorf("invalid targets")
}
if c.EnableRegexp {
if c.FirstPacketTimeout == 0 {
c.FirstPacketTimeout = 5000
}
}
for i, v := range c.Targets {
if v.Address == "" {
return fmt.Errorf("invalid address at pos %d", i)
}
if c.EnableRegexp {
r, err := regexp.Compile(v.Regexp)
if err != nil {
return fmt.Errorf("invalid regexp at pos %d : %s", i, err.Error())
}
v.regexp = r
}
}
return nil
}