Golang base reads INI
Extract the contents of the INI file using read file mode
Content of the test.ini file
[aa]
a1=11
a2=22
[bb]
b1=33
b2=44
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
func main() {
fmt.Println(readFileIni("bb", "b2"))
}
func readFileIni(master, detail string) string {
var result string = ""
file, err := os.Open("test.ini")
if err != nil {
fmt.Println(err)
}
defer file.Close()
var sectionName string
reader := bufio.NewScanner(file)
for reader.Scan() {
linestr := reader.Text()
strings.TrimSpace(linestr)
if linestr == "" {
continue
}
if linestr[0] == ';' {
continue
}
if string(linestr[0]) == "[" && string(linestr[len(linestr)-1]) == "]" {
sectionName = linestr[1 : len(linestr)-1]
} else if sectionName == master {
pair := strings.Split(linestr, "=")
if len(pair) == 2 {
key := strings.TrimSpace(pair[0])
if key == detail {
result = pair[1]
}
}
}
}
return result
}
First, open the INI file, and then read the file line by line. Remove the space, comment and blank line of each line, and extract the data starting with [and ending with] to give sectionName. If you need to obtain the same name as sectionName, you can continue to obtain the sub-configuration. The subconfiguration divides keys and values according to =.