生活的道路一旦选定,就要勇敢地走到底,决不回头。

发掘积累过程的快感

首页 » BIBLE模型 » GoLang » gopkg.in/ini.v1 使用简介

gopkg.in/ini.v1 使用简介


下载安装

最低要求安装 Go 语言版本为 1.6 ,$ go get gopkg.in/ini.v1,如需更新请添加 -u 选项。

开始使用

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

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

完美!这个例子很简单,展示的也只是极其小部分的功能,想要完全掌握还需要多读多看,毕竟学无止境嘛。

从数据源加载

就像之前说的,从多个数据源加载配置是基本操作。

那么,到底什么是 数据源 呢?

一个 数据源 可以是 []byte 类型的原始数据,string 类型的文件路径或 io.ReadCloser。您可以加载 任意多个 数据源。如果您传递其它类型的数据源,则会直接返回错误。

cfg, err := ini.Load(
    []byte("raw data"), // 原始数据
    "filename",         // 文件路径
    ioutil.NopCloser(bytes.NewReader([]byte("some other data"))),
)

或者从一个空白的文件开始:

cfg := ini.Empty()

当您在一开始无法决定需要加载哪些数据源时,仍可以使用 Append() 在需要的时候加载它们。

err := cfg.Append("other file", []byte("other raw data"))

当您想要加载一系列文件,但是不能够确定其中哪些文件是不存在的,可以通过调用函数 LooseLoad() 来忽略它们。

cfg, err := ini.LooseLoad("filename", "filename_404")

更牛逼的是,当那些之前不存在的文件在重新调用 Reload() 方法的时候突然出现了,那么它们会被正常加载。

数据覆写

在加载多个数据源时,如果某一个键在一个或多个数据源中出现,则会出现数据覆写。该键从前一个数据源读取的值会被下一个数据源覆写。

举例来说,如果加载两个配置文件 my.inimy.ini.local 开始使用中的输入和输出文件),app_mode 的值会是 production 而不是 development

cfg, err := ini.Load("my.ini", "my.ini.local")
...

cfg.Section("").Key("app_mode").String() // production

数据覆写只有在一种情况下不会触发,即使用 ShadowLoad 加载数据源。

跳过无法识别的数据行

某些情况下,您的配置文件可能包含非键值对的数据行,解析器默认会报错并终止解析。如果您希望解析器能够忽略并它们完成剩余内容的解析,则可以通过如下方法实现:

cfg, err := ini.LoadSources(ini.LoadOptions{
    SkipUnrecognizableLines: true,
}, "other.ini")

保存配置

终于到了这个时刻,是时候保存一下配置了。

比较原始的做法是输出配置到某个文件:

// ...
err = cfg.SaveTo("my.ini")
err = cfg.SaveToIndent("my.ini", "\t")

另一个比较高级的做法是写入到任何实现 io.Writer 接口的对象中:

// ...
cfg.WriteTo(writer)
cfg.WriteToIndent(writer, "\t")

默认情况下,空格将被用于对齐键值之间的等号以美化输出结果,以下代码可以禁用该功能:

ini.PrettyFormat = false
互联网信息太多太杂,各互联网公司不断推送娱乐花边新闻,SNS,微博不断转移我们的注意力。但是,我们的时间和精力却是有限的。这里是互联网浩瀚的海洋中的一座宁静与美丽的小岛,供开发者歇息与静心潜心修炼。 “Bible”是圣经,有权威的书,我们的本意就是为开发者提供真正有用的的资料。 我的电子邮件 1217179982@qq.com,您在开发过程中遇到任何问题,欢迎与我联系。
Copyright © 2024. All rights reserved. 本站由 Helay 纯手工打造. 蜀ICP备15017444号