处理Go程序的配置参数的首选方法是什么(在其他上下文中可能使用属性文件或ini文件的那种东西)?


当前回答

看看贡菲

// 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)

其他回答

看看贡菲

// 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。它工作。但我讨厌必须创建我可能要设置的确切字段和类型的结构体。对我来说,这是一种痛苦。我注意到,我能找到的所有配置选项都使用这种方法。也许我在动态语言方面的背景让我看不到这种冗长的好处。我制作了一个新的简单配置文件格式,以及一个更动态的库来读取它。

https://github.com/chrisftw/ezconf

我对围棋世界很陌生,所以这可能不是围棋的方式。但是它很有效,非常快,而且使用起来超级简单。

Pros

超级简单的 更少的代码

Cons

没有数组或Map类型 非常平面的文件格式 非标准的conf文件 它有一个内置的小约定,我现在在围棋社区普遍不赞成这个约定。(在config目录中查找配置文件)

JSON格式非常适合我。的 标准库提供了缩进写入数据结构的方法,因此它是相当 可读。

看看这条高朗坚果线。

JSON的好处是它相当简单,易于解析和人类可读/编辑 同时为列表和映射提供语义(这可能会变得非常方便) 不是许多ini类型配置解析器的情况。

使用示例:

conf.json:

{
    "Users": ["UserA","UserB"],
    "Groups": ["GroupA"]
}

程序读取配置

import (
    "encoding/json"
    "os"
    "fmt"
)

type Configuration struct {
    Users    []string
    Groups   []string
}

file, _ := os.Open("conf.json")
defer file.Close()
decoder := json.NewDecoder(file)
configuration := Configuration{}
err := decoder.Decode(&configuration)
if err != nil {
  fmt.Println("error:", err)
}
fmt.Println(configuration.Users) // output: [UserA, UserB]

Viper是一个golang配置管理系统,可以使用JSON、YAML和TOML。看起来很有趣。

对于更复杂的数据结构,我通常使用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")

它还支持切片值,因此您可以允许多次指定一个键和其他类似的好特性。