golang读取ini配置文件

 

 example.ini

[core]
repositoryformatversion = 0

filemode = false
bare = false
logallrefupdates = true
symlinks = false
ignorecase = true
hideDotFiles = dotGitOnly

[remote "origin"]
url = https://github.com/davyxu/cellnet
fetch = +refs/heads/*:refs/remotes/origin/*

[branch "master"]
remote = origin
merge = refs/heads/master

  

golang读取ini配置文件

inireader.go

 1 package main
 2 
 3 import (
 4     "bufio"
 5     "fmt"
 6     "os"
 7     "strings"
 8 )
 9 
10 // 根据文件名,段名,键名获取ini的值
11 func getValue(filename, expectSection, expectKey string) string {
12 
13     // 打开文件
14     file, err := os.Open(filename)
15 
16     // 文件找不到,返回空
17     if err != nil {
18         return ""
19     }
20 
21     // 在函数结束时,关闭文件
22     defer file.Close()
23 
24     // 使用读取器读取文件
25     reader := bufio.NewReader(file)
26 
27     // 当前读取的段的名字
28     var sectionName string
29 
30     for {
31 
32         // 读取文件的一行
33         linestr, err := reader.ReadString('\n')
34         if err != nil {
35             break
36         }
37 
38         // 切掉行的左右两边的空白字符
39         linestr = strings.TrimSpace(linestr)
40 
41         // 忽略空行
42         if linestr == "" {
43             continue
44         }
45 
46         // 忽略注释
47         if linestr[0] == ';' {
48             continue
49         }
50 
51         // 行首和尾巴分别是方括号的,说明是段标记的起止符
52         if linestr[0] == '[' && linestr[len(linestr)-1] == ']' {
53 
54             // 将段名取出
55             sectionName = linestr[1 : len(linestr)-1]
56 
57             // 这个段是希望读取的
58         } else if sectionName == expectSection {
59 
60             // 切开等号分割的键值对
61             pair := strings.Split(linestr, "=")
62 
63             // 保证切开只有1个等号分割的简直情况
64             if len(pair) == 2 {
65 
66                 // 去掉键的多余空白字符
67                 key := strings.TrimSpace(pair[0])
68 
69                 // 是期望的键
70                 if key == expectKey {
71 
72                     // 返回去掉空白字符的值
73                     return strings.TrimSpace(pair[1])
74                 }
75             }
76 
77         }
78 
79     }
80 
81     return ""
82 }
83 
84 func main() {
85 
86     fmt.Println(getValue("example.ini", "remote \"origin\"", "fetch"))
87 
88     fmt.Println(getValue("example.ini", "core", "hideDotFiles"))
89 }

 运行结果:

 

posted on 2021-09-14 21:24  yuzyong  阅读(531)  评论(0编辑  收藏  举报