-
Notifications
You must be signed in to change notification settings - Fork 5
/
config.go
195 lines (173 loc) · 5.15 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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
package nimo
import (
"bufio"
"errors"
"fmt"
"os"
"path/filepath"
"reflect"
"regexp"
"strconv"
"strings"
"time"
)
const (
DefaultSeparator = ";"
GenericTypeRaw = 1
GenericTypeDate = 2
)
var onlyAlpha = regexp.MustCompile("^[a-zA-Z0-9_-]+")
// ConfigLoader load config from file
type ConfigLoader struct {
conf *os.File
// date format string
format string
// string slice separator
separator string
}
// NewConfigLoader new loader
func NewConfigLoader(file *os.File) *ConfigLoader {
return &ConfigLoader{conf: file, separator: DefaultSeparator}
}
func (loader *ConfigLoader) SetDateFormat(format string) {
loader.format = format
}
func (loader *ConfigLoader) SetSliceSeparator(sep string) {
loader.separator = sep
}
// Load load config from file to target's field by reflect
func (loader *ConfigLoader) Load(target interface{}) error {
if target == nil {
return errors.New("target is nil error")
}
// fetch all target's field member
instance := reflect.ValueOf(target).Elem()
if !instance.IsValid() || instance.Kind() != reflect.Struct {
return errors.New("target is not a valid struct type")
}
// file content reader. handled line by line
lines := readAllLines(*bufio.NewReader(loader.conf))
if len(lines) == 0 {
// empty file or have error
return errors.New("configuration file is empty or read error")
}
for _, line := range lines {
pair := strings.SplitN(line, "=", 2)
key := strings.Trim(pair[0], " ")
if len(pair) != 2 || !onlyAlpha.MatchString(key) {
return fmt.Errorf("error confiugre key line found. key is %s", key)
}
value := strings.Trim(pair[1], " ")
// key is good. look up the matching tag
var err error
var found string
var genericType int
if found, genericType, err = lookupTagMember(target, key); err != nil {
// not found in struct, give error
return fmt.Errorf("couldn't found structure key's tag '%s'. one must be tagged", key)
}
field := instance.FieldByName(found)
if !field.IsValid() || !field.CanSet() {
return fmt.Errorf("structure key '%s' is not accessable", key)
}
// set config's value
switch field.Kind() {
case reflect.String: // for string
field.SetString(value)
case reflect.Bool: // for bool
if v, err := strconv.ParseBool(value); err == nil {
field.SetBool(v)
} else {
return fmt.Errorf("boolean key %s wrong format %v", key, value)
}
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: // for numberic
if genericType == GenericTypeDate {
if t, e := time.ParseInLocation(loader.format, value, time.UTC); e == nil {
field.SetInt(t.Unix())
} else {
return fmt.Errorf("integer conver to date format [%s] from (%s)", loader.format, value)
}
} else if v, err := strconv.ParseInt(value, 10, 64); err == nil {
field.SetInt(v)
} else {
return fmt.Errorf("integer key %s wrong format %v", key, value)
}
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
if v, err := strconv.ParseUint(value, 10, 64); err == nil {
field.SetUint(v)
} else {
return fmt.Errorf("unsigned integer key %s wrong format %v", key, value)
}
case reflect.Slice: // for slice
if items, err := loader.extractAsList(value); err == nil {
filtered := make([]string, 0, len(items))
for _, item := range items {
if s := strings.TrimSpace(item); len(s) != 0 {
filtered = append(filtered, s)
}
}
field.Set(reflect.ValueOf(filtered))
} else {
return err
}
}
}
return nil
}
func (loader *ConfigLoader) extractAsList(value string) ([]string, error) {
if strings.HasPrefix(value, "@@") {
// we need to fetch the content from specific file
if ref, err := os.Open(fmt.Sprintf("%s%c%s", filepath.Dir(loader.conf.Name()),
filepath.Separator, value[2:])); err == nil {
return readAllLines(*bufio.NewReader(ref)), nil
} else {
return nil, err
}
}
return strings.Split(value, DefaultSeparator), nil
}
func readAllLines(reader bufio.Reader) (lines []string) {
buffered := make([]byte, 0, 8192)
for {
if buf, isPrefix, err := reader.ReadLine(); err != nil {
break
} else if isPrefix {
buffered = append(buffered, buf...)
} else {
if len(buffered) != 0 {
buffered = append(buffered, buf...)
buf = buffered
}
line := strings.Trim(string(buf), " \r\n")
if len(line) != 0 && !isComment(line) {
lines = append(lines, line)
}
if len(buffered) != 0 {
buffered = make([]byte, 0, 8192)
}
}
}
if len(buffered) != 0 {
line := strings.Trim(string(buffered), " \r\n")
if len(line) != 0 && !isComment(line) {
lines = append(lines, line)
}
}
return lines
}
func lookupTagMember(target interface{}, tag string) (string, int, error) {
total := reflect.ValueOf(target).Elem().NumField()
types := reflect.TypeOf(target)
for i := 0; i != total; i++ {
if types.Elem().Field(i).Tag.Get("config") == tag {
if types.Elem().Field(i).Tag.Get("type") == "date" {
return types.Elem().Field(i).Name, GenericTypeDate, nil
}
return types.Elem().Field(i).Name, GenericTypeRaw, nil
}
}
return "", -1, fmt.Errorf("no tagged field [%s] found", tag)
}
func isComment(line string) bool {
return strings.HasPrefix(line, "#")
}