Go开源项目 - goconfig 使用方法

goconfig 是Revel用到的一个开源工具, 它实现了一个基础的配置文件解析器语言, 它的结构类似于微软的Windows INI文件.

配置文件由几部分组成, 由"[section]"做头部紧接着"name:value"键值对, 也可以用"name=value". 注意空格将被从values中删除. 在相同的section可选的value能包含涉及其他values格式化字符串, 或values在一个特殊的DEFAULT部分. 另外defaults可以在初始化和检索时被提供. 注释字符时 ";" 或 "#", 一个注释可以在任何一行开始出, 包括在相同的行的参数后或section声明.

例如:

[My Section]
foodir: %(dir)s/whatever
dir=foo

"*%(dir)s*"将被dir的值foo替换, 全部的引用将按需解释.

功能和工作流是松散的基于python标准库的configparser包.

安装

go get github.com/kless/goconfig/config

运行测试

cd ${GOPATH//:*}/src/github.com/kless/goconfig/config && go test && cd -

操作指令

下面是一个简单的配置文件:

[DEFAULT]
host: www.example.com
protocol: http://
base-url: %(protocol)s%(host)s

[service-1]
url: %(base-url)s/some/path
delegation: on
maxclients: 200 # do not set this higher
comments: This is a multi-line
    entry   # And this is a comment

来读一下这个配置文件:

c, _ := config.ReadDefault("config.cfg")

c.String("service-1", "url")
// result is string "http://www.example.com/some/path"

c.Int("service-1", "maxclients")
// result is int 200

c.Bool("service-1", "delegation")
// result is bool true

c.String("service-1", "comments")
// result is string "This is a multi-line\nentry"

注意: 支持展开变量(像这样%(base-url)s), 它从保留的section名称[DEFAULT]中读取.

一个新的配置文件也能用代码创建:

c := config.NewDefault()
c.AddSection("Section")
c.AddOption("Section", "option", "value")
c.WriteFile("config.cfg", 0644, "A header for this file")

创建的文件内容如下:

# A header for this file

[Section]
option: value

注意section, options和vaules全部是大小写敏感的.

至此结束.