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 }
運行結果: