/
SourceProperties.go
99 lines (80 loc) · 1.66 KB
/
SourceProperties.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
package props
import (
"io"
"bufio"
"bytes"
"unicode"
"os"
)
type SourceProperties struct {
cache map[string]string
}
func NewSourceProperties() *SourceProperties {
return &SourceProperties{
cache: make(map[string]string),
}
}
func (s *SourceProperties) LoadFile(filename string) error {
file, err := os.Open(filename)
if nil != err {
return err
}
defer file.Close()
return s.Load(file)
}
func (s *SourceProperties) Load(reader io.Reader) error {
// 创建一个扫描器
scanner := bufio.NewScanner(reader)
for scanner.Scan() {
// 逐行读取
line := scanner.Bytes()
// 遇到空行
if 0 == len(line) {
continue
}
// 找到第一个非空白字符
pos := bytes.IndexFunc(line, func(r rune) bool {
return !unicode.IsSpace(r)
})
// 遇到空白行
if -1 == pos {
continue
}
// 遇到注释行
if '#' == line[pos] {
continue
}
if '!' == line[pos] {
continue
}
// 找到第一个等号的位置
end := bytes.IndexFunc(line[pos+1:], func(r rune) bool {
return ('=' == r) || (':' == r)
})
// 没有=,说明该配置项只有key
key := ""
value := ""
if -1 == end {
key = string(bytes.TrimRightFunc(line[pos:], func(r rune) bool {
return unicode.IsSpace(r)
}))
} else {
key = string(bytes.TrimRightFunc(line[pos:pos+1+end], func(r rune) bool {
return unicode.IsSpace(r)
}))
value = string(bytes.TrimSpace(line[pos+1+end+1:]))
}
s.cache[key] = value
}
if err := scanner.Err(); nil != err {
return err
}
return nil
}
func (s SourceProperties) Find(key string) (string, bool) {
val, ok := s.cache[key]
if !ok {
return "", false
}
return val, true
}