指一条配置,就像key = value这样的。git
sections是parameters的集合,sections必须独占一行而且用[]括起来。github
sections没有明显的结束方式,一个sections的开始就是另外一个sections的结束。sql
指INI配置文件的注释,以 ; 开头。shell
[DataBase] ServerIP=********** ServerPort=8080 ControlConnectString=QWDJ7+XH6oWaANAGhVgh5/5UxYrA2rfz/ufAkDlN1H9Tw+v7Z0SoCfR+wYdyzCjF/ANUfPxlO6cLDAhm4xxmbADyKs6zmkWuGQNgDZmPx6c= ControlConnectCategory=0 [LogonInfo] SaveUserID=Y UserID=admin DBServer=AppDB DBCenter=Demo [UserConfig] OpenDownloadFileAtOnec=Y WindowStyle=DevExpress Dark Style [Language] Language=CHS [AutoUpdate] Version=1.1
这里咱们使用GitHub上的第三方库(https://github.com/go-ini)
。session
**Package ini provides INI file read and write functionality in Go. **app
The minimum requirement of Go is 1.6.dom
$ go get gopkg.in/ini.v1
Please add -u
flag to update in the future.ide
咱们将经过一个很是简单的例子来了解如何使用。ui
首先,咱们须要在任意目录建立两个文件(my.ini
和 main.go
),在这里咱们选择 /tmp/ini
目录。指针
$ mkdir -p /tmp/ini $ cd /tmp/ini $ touch my.ini main.go $ tree . . ├── main.go └── my.ini 0 directories, 2 files
如今,咱们编辑 my.ini
文件并输入如下内容(部份内容来自 Grafana)。
# possible values : production, development app_mode = development [paths] # Path to where grafana can store temp files, sessions, and the sqlite3 db (if that is used) data = /home/git/grafana [server] # Protocol (http or https) protocol = http # The http port to use http_port = 9999 # Redirect to correct domain if host header does not match domain # Prevents DNS rebinding attacks enforce_domain = true
很好,接下来咱们须要编写 main.go
文件来操做刚才建立的配置文件。
package main import ( "fmt" "os" "gopkg.in/ini.v1" ) func main() { cfg, err := ini.Load("my.ini")//初始化一个cfg if err != nil { fmt.Printf("Fail to read file: %v", err) os.Exit(1) } // 典型读取操做,默认分区可使用空字符串表示 fmt.Println("App Mode:", cfg.Section("").Key("app_mode").String()) fmt.Println("Data Path:", cfg.Section("paths").Key("data").String()) // 咱们能够作一些候选值限制的操做 fmt.Println("Server Protocol:", cfg.Section("server").Key("protocol").In("http", []string{"http", "https"})) // 若是读取的值不在候选列表内,则会回退使用提供的默认值 fmt.Println("Email Protocol:", cfg.Section("server").Key("protocol").In("smtp", []string{"imap", "smtp"})) // 试一试自动类型转换 fmt.Printf("Port Number: (%[1]T) %[1]d\n", cfg.Section("server").Key("http_port").MustInt(9999)) fmt.Printf("Enforce Domain: (%[1]T) %[1]v\n", cfg.Section("server").Key("enforce_domain").MustBool(false)) // 差很少了,修改某个值而后进行保存 cfg.Section("").Key("app_mode").SetValue("production") cfg.SaveTo("my.ini.local") }
运行程序,咱们能够看下如下输出
$ go run main.go App Mode: development Data Path: /home/git/grafana Server Protocol: http Email Protocol: smtp Port Number: (int) 9999 Enforce Domain: (bool) true $ cat my.ini.local # possible values : production, development app_mode = production [paths] # Path to where grafana can store temp files, sessions, and the sqlite3 db (if that is used) data = /home/git/grafana ...
想要使用更加面向对象的方式玩转 INI 吗?好主意。
配置文件以下:
Name = Unknwon age = 21 Male = true Born = 1993-01-01T20:17:05Z [Note] Content = Hi is a good man! Cities = HangZhou, Boston
//按照配置文件的内容构造结构体 type Note struct { Content string Cities []string } type Person struct { Name string Age int `ini:"age"`//这里须要用到反射,由于和ini文件的字段不一样 Male bool Born time.Time Note Created time.Time `ini:"-"` } func main() { cfg, err := ini.Load("path/to/ini") // ... p := new(Person)//初始化一个结构体,返回指向他的指针 err = cfg.MapTo(p) // ... // 一切竟能够如此的简单。 err = ini.MapTo(p, "path/to/ini")//核心代码 // ... // 嗯哼?只须要映射一个分区吗? n := new(Note) err = cfg.Section("Note").MapTo(n) // ... }
结构的字段怎么设置默认值呢?很简单,只要在映射以前对指定字段进行赋值就能够了。若是键未找到或者类型错误,该值不会发生改变。
// ... p := &Person{ Name: "Joe", } // ..
type Embeded struct { Dates []time.Time `delim:"|" comment:"Time data"` Places []string `ini:"places,omitempty"` None []int `ini:",omitempty"` } type Author struct { Name string `ini:"NAME"` Male bool Age int `comment:"Author's age"` GPA float64 NeverMind string `ini:"-"` *Embeded `comment:"Embeded section"` } func main() { a := &Author{"Unknwon", true, 21, 2.8, "", &Embeded{ []time.Time{time.Now(), time.Now()}, []string{"HangZhou", "Boston"}, []int{}, }} cfg := ini.Empty()//初始化一个空配置文件 err = ini.ReflectFrom(cfg, a)//核心代码 // ... }
瞧瞧,奇迹发生了。
NAME = Unknwon Male = true ; Author's age Age = 21 GPA = 2.8 ; Embeded section [Embeded] ; Time data Dates = 2015-08-07T22:14:22+08:00|2015-08-07T22:14:22+08:00 places = HangZhou,Boston