Go语言中INI配置文件格式解析

init配置文件与解析

INI配置文件有三要素

  1. parameters

  指一条配置,就像key = value这样的。

  1. sections

  sections是parameters的集合,sections必须独占一行并且用[]括起来。

  sections没有明显的结束方式,一个sections的开始就是另一个sections的结束。

  1. comments

  指INI配置文件的注释,以 ; 开头。

[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

init 配置文件的解析

这里我们使用GitHub上的第三方库(https://github.com/go-ini)

img

**Package ini provides INI file read and write functionality in Go. **

安装

The minimum requirement of Go is 1.6.

$ go get gopkg.in/ini.v1

Please add -u flag to update in the future.

开始使用

我们将通过一个非常简单的例子来了解如何使用。

首先,我们需要在任意目录创建两个文件(my.inimain.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

参考文献:https://ini.unknwon.cn/docs/advanced/map_and_reflect

posted @ 2020-05-03 11:13  wind-zhou  Views(2071)  Comments(1Edit  收藏  举报