-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprop.go
More file actions
73 lines (65 loc) · 1.71 KB
/
prop.go
File metadata and controls
73 lines (65 loc) · 1.71 KB
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
// package prop attempts to provide a similar usage with Properties in java.
// the line starts with '#' is a comment.
// blank line is allowed.
// otherwise, the line should contain only one "=", and the words before "=" become key, the words after "=" become value.
// key and value will be trimed, after trimming, if key or value equals "", it's invalid.
package prop
import (
"os"
"io"
"strings"
"bufio"
"errors"
"strconv"
)
// Load loads properties from propPath.
func Load(propPath string) (map[string]string, error) {
prop := make(map[string]string)
file, err := os.Open(propPath)
if err != nil {
return nil, err
}
defer file.Close()
count := 0
reader := bufio.NewReader(file)
for {
count++
linebytes, isPrefix, err := reader.ReadLine()
if err != nil {
if err == io.EOF {
return prop, nil
}
return nil, err
}
if isPrefix {
err = errors.New("contains too long line at line " + strconv.Itoa(count))
return nil, err
}
// check line
line := string(linebytes)
line = strings.TrimSpace(line)
if line == "" || strings.HasPrefix(line, "#") {
continue
}
equalNum := strings.Count(line, "=")
if equalNum != 1 {
err = errors.New("invalid format at line " + strconv.Itoa(count))
return nil, err
}
// check key and value
equalIndex := strings.Index(line, "=")
key := strings.TrimSpace(string(line[0:equalIndex]))
value := strings.TrimSpace(string(line[equalIndex+1:]))
if key == "" || value == "" {
err = errors.New("invalid format at line " + strconv.Itoa(count))
return nil, err
}
// check duplicate key
if _, ok := prop[key]; ok {
err = errors.New("contains duplicate key: " + key)
return nil, err
}
prop[key] = value
}
return prop, nil
}