-
Notifications
You must be signed in to change notification settings - Fork 2
/
goini.go
119 lines (97 loc) · 2.16 KB
/
goini.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
package goini
import (
"bufio"
"errors"
"fmt"
"os"
"strconv"
"strings"
)
type errorString struct {
s string
}
// IniRow contains parsed line section, param and value.
type IniRow struct {
section string
param string
value string
}
// Ini struct contains parsed ini file lines.
type Ini struct {
Elements []IniRow
}
func (e *errorString) Error() string {
return e.s
}
// New returns new error.
func New(text string) error {
return &errorString{text}
}
// getValue returns value as string.
func getValue(ini *Ini, section string, param string) string {
for _, element := range ini.Elements {
if element.section == section && element.param == param {
return element.value
break
//fmt.Printf("Results: %v\n", element)
}
}
return ""
}
// Load function read file to memory and return Ini struct.
func Load(conf string) (*Ini, error) {
file, err := os.Open(conf)
if err != nil {
return nil, errors.New(fmt.Sprintf("error opening file: %v\n", err))
}
defer file.Close()
arr := new(Ini)
scanner := bufio.NewScanner(file)
section := ""
for scanner.Scan() {
line := scanner.Text()
line = strings.TrimSpace(line)
if len(line) > 0 && line[0:1] != ";" {
if len(line) >= 3 && line[0:1] == "[" /*&& line[(len(line)-1):1] == "]"*/ {
section = line[1 : len(line)-1]
} else {
if strings.Contains(line, "=") {
KeyVal := strings.Split(line, "=")
row := IniRow{
section: section,
param: strings.TrimSpace(KeyVal[0]),
value: strings.TrimSpace(KeyVal[1]),
}
arr.Elements = append(arr.Elements, row)
}
}
}
}
return arr, nil
}
// Str returns string type value.
func (ini *Ini) Str(section, param string) string {
return getValue(ini, section, param)
}
// Int returns integer type value.
func (ini *Ini) Int(section, param string) int {
val := getValue(ini, section, param)
if val == "" {
return 0
} else {
i, err := strconv.Atoi(val)
if err != nil {
return 0
} else {
return i
}
}
}
// Bool returns boolean type value.
func (ini *Ini) Bool(section, param string) bool {
val := getValue(ini, section, param)
if val == "true" || val == "1" {
return true
}
return false
}