golang 读取ini配置文件

ini配置文件

1
2
3
4
[Host]
host="127.0.0.1"
name="roddy"
dbpath="/user/local/mysql/bin/"

安装gcfg.v1

1
go get gopkg.in/gcfg.v1

解析ini

1
2
3
4
5
6
7
8
9
10
11
12
13
14

config := struct {
Host struct{
Host string
Name string
DBPath string
}
}

err := gcfg.ReadFileInto(&config, "config.ini")
if err != nil {
fmt.Printf("读取文件失败,err:%v\n",err)
return
}

多Section解析

多节点配置文件

1
2
3
4
5
6
7
8
9
[Host]
host="127.0.0.1"
name="roddy"
dbpath="/user/local/mysql/bin/"

[Config]
path="/etc/sys.ini"
user="roddy"
port=3388

解析

1
2
3
4
5
6
7
8
9
10
11
12
13
14
config := struct {
Host struct{
Host string
Name string
DBPath string
}

Config struct{
Path string
User string
Port int

}
}{}

完整实例

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
package main

import (
"fmt"
"gopkg.in/gcfg.v1"
)

func main() {
config := struct {
Host struct{
Host string
Name string
DBPath string
}

Config struct{
Path string
User string
Port int

}
}{}


fmt.Printf("xxx")
err := gcfg.ReadFileInto(&config, "config.ini")
if err != nil {
fmt.Printf("读取文件失败,err:%v\n",err)
return
}


fmt.Println(config.Host.Host)
fmt.Println(config.Host.Name)
fmt.Println(config.Host.DBPath)


fmt.Println("----------------")
fmt.Println(config.Config.Path)
fmt.Println(config.Config.Port)
fmt.Println(config.Config.User)


}