处理Go程序的配置参数的首选方法是什么(在其他上下文中可能使用属性文件或ini文件的那种东西)?
当前回答
https://github.com/spf13/viper和https://github.com/zpatrick/go-config是非常好的配置文件库。
其他回答
看看贡菲
// load
config, _ := gonfig.FromJson(myJsonFile)
// read with defaults
host, _ := config.GetString("service/host", "localhost")
port, _ := config.GetInt("service/port", 80)
test, _ := config.GetBool("service/testing", false)
rate, _ := config.GetFloat("service/rate", 0.0)
// parse section into target structure
config.GetAs("service/template", &template)
对于更复杂的数据结构,我通常使用JSON。缺点是,您很容易以一堆代码来告诉用户错误在哪里、各种边缘情况和其他情况。
对于基本配置(api密钥,端口号,…)我在使用gcfg包时运气非常好。它基于git配置格式。
从文档中可以看到:
示例配置:
; Comment line
[section]
name = value # Another comment
flag # implicit value for bool is true
结构:
type Config struct {
Section struct {
Name string
Flag bool
}
}
读取它所需的代码:
var cfg Config
err := gcfg.ReadFileInto(&cfg, "myconfig.gcfg")
它还支持切片值,因此您可以允许多次指定一个键和其他类似的好特性。
另一种选择是使用TOML,这是Tom Preston-Werner创建的一种类似ini的格式。我为它构建了一个经过广泛测试的Go解析器。您可以像这里建议的其他选项一样使用它。例如,如果您在something.toml中有这个TOML数据
Age = 198
Cats = [ "Cauchy", "Plato" ]
Pi = 3.14
Perfection = [ 6, 28, 496, 8128 ]
DOB = 1987-07-05T05:45:00Z
然后你可以把它加载到你的Go程序中
type Config struct {
Age int
Cats []string
Pi float64
Perfection []int
DOB time.Time
}
var conf Config
if _, err := toml.DecodeFile("something.toml", &conf); err != nil {
// handle error
}
我用golang写了一个简单的ini配置库。
https://github.com/c4pt0r/cfg
gorroutine安全,易于使用
package cfg
import (
"testing"
)
func TestCfg(t *testing.T) {
c := NewCfg("test.ini")
if err := c.Load() ; err != nil {
t.Error(err)
}
c.WriteInt("hello", 42)
c.WriteString("hello1", "World")
v, err := c.ReadInt("hello", 0)
if err != nil || v != 42 {
t.Error(err)
}
v1, err := c.ReadString("hello1", "")
if err != nil || v1 != "World" {
t.Error(err)
}
if err := c.Save(); err != nil {
t.Error(err)
}
}
=================== 更新 =======================
最近,我需要一个INI解析器与节支持,我写了一个简单的包:
github.com/c4pt0r/cfg
你可以像使用"flag"包一样解析INI:
package main
import (
"log"
"github.com/c4pt0r/ini"
)
var conf = ini.NewConf("test.ini")
var (
v1 = conf.String("section1", "field1", "v1")
v2 = conf.Int("section1", "field2", 0)
)
func main() {
conf.Parse()
log.Println(*v1, *v2)
}
Viper是一个golang配置管理系统,可以使用JSON、YAML和TOML。看起来很有趣。