-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconfig.go
101 lines (91 loc) · 2.02 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
94
95
96
97
98
99
100
101
package main
import (
"bufio"
"fmt"
"io"
"os"
"regexp"
"strings"
)
type configActions int
const (
actionNone configActions = 0
actionBlock configActions = 1
actionProxy configActions = 2
actionDirect configActions = 4
actionForceHTTPS configActions = 8
actionFragment configActions = 16
)
type configCase struct {
mask *regexp.Regexp
actions configActions
}
type config struct {
cases []configCase
}
func compileMask(mask string) *regexp.Regexp {
mask = regexp.QuoteMeta(mask)
mask = strings.Replace(mask, "\\?", ".", -1)
mask = strings.Replace(mask, "\\*", ".*", -1)
return regexp.MustCompile(`\A(?:` + mask + `)\z`)
}
var actionSeparator = regexp.MustCompile(`[ \t]+`)
var actionFromString = map[string]configActions{
"block": actionBlock,
"proxy": actionProxy,
"direct": actionDirect,
"https": actionForceHTTPS,
"fragment": actionFragment,
}
func loadConfigReader(reader io.Reader) (*config, error) {
r := bufio.NewReader(reader)
c := &config{}
for {
line, err := r.ReadString('\n')
if err != nil {
if err != io.EOF {
return nil, err
}
if line == "" {
break
}
// parse incomplete lines
} else {
// strip the delimiter
line = line[:len(line)-1]
}
line = strings.TrimSpace(line)
if line == "" || line[0] == '#' {
// skip empty lines and comments
continue
}
parts := actionSeparator.Split(line, -1)
if len(parts) <= 1 {
return nil, fmt.Errorf("cannot parse: %s", line)
}
var actions configActions
for _, text := range parts[1:] {
action, ok := actionFromString[strings.ToLower(text)]
if !ok {
return nil, fmt.Errorf("unknown action: %q", text)
}
actions |= action
}
c.cases = append(c.cases, configCase{
mask: compileMask(parts[0]),
actions: actions,
})
}
return c, nil
}
func loadConfigFile(filename string) (*config, error) {
f, err := os.Open(filename)
if err != nil {
if os.IsNotExist(err) {
return &config{}, nil
}
return nil, err
}
defer f.Close()
return loadConfigReader(f)
}