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全部是大小寫敏感的.
至此結束.