直接上代碼:
package main
import (
"bytes"
"fmt"
"os"
"strings"
)
/*
解析ini檔案
*/
func nIndex(str string, c rune, count int) []int {
res := make([]int, 0)
amount := 0
for i, s := range str {
if amount == count {
break
}
if s == c {
res = append(res, i)
amount++
}
}
return res
}
type IParser interface {
getSections() []string
getConfig() map[string]map[string]string
}
type ConfigParser struct {
path string
config map[string]map[string]string
}
func MakeParser(path string) *ConfigParser {
contentByte := bytes.Buffer{}
file, _ := os.Open(path)
buffer := make([]byte, 2048)
var config = make(map[string]map[string]string)
for {
n, err := file.Read(buffer)
if err != nil {
break
}
contentByte.Write(buffer[:n])
}
content := contentByte.String()
splitStr := "\n"
if strings.Contains(content, "\r\n") {
splitStr = "\r\n"
}
lines := strings.Split(content, splitStr)
line := ""
i := 0
length := len(lines)
for i < length {
line = lines[i]
trimmed := strings.Trim(line, " ")
if len(trimmed) < 1 || trimmed[0] == '#' {
i++
continue
}
if trimmed[0] == '[' && trimmed[len(trimmed)-1] == ']' {
section := make(map[string]string)
config[trimmed[1:len(trimmed)-1]] = section
for {
i++
if i >= length {
break
}
line = lines[i]
trimmed := strings.Trim(line, " ")
if trimmed[0] == '[' {
break
}
if len(trimmed) < 1 || trimmed[0] == '#' || !strings.Contains(trimmed, "=") {
continue
}
if trimmed[0] != '"' {
indexEq := strings.Index(trimmed, "=")
if indexEq == len(trimmed)-1 {
section[trimmed[:indexEq]] = ""
} else {
section[trimmed[:indexEq]] = trimmed[indexEq+1:]
}
} else {
indexEq := nIndex(trimmed, '"', 2)
if indexEq[1] == 0 || indexEq[1] == len(trimmed)-1 || trimmed[indexEq[1]+1] != '=' {
continue
}
if indexEq[1]+2 >= len(trimmed) {
section[trimmed[1:indexEq[1]]] = ""
} else {
section[trimmed[1:indexEq[1]]] = trimmed[indexEq[1]+2:]
}
}
}
} else {
i++
}
}
parser := ConfigParser{}
parser.config = config
return &parser
}
func (parser *ConfigParser) getConfig() map[string]map[string]string {
return parser.config
}
func (parser *ConfigParser) getSections() []string {
sections := make([]string, 0)
for k := range parser.config {
sections = append(sections, k)
}
return sections
}
func main() {
var parser IParser
parser = MakeParser("config.ini")
config := parser.getConfig()
sections := parser.getSections()
fmt.Println(config)
fmt.Println(sections)
}