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


当前回答

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

其他回答

https://github.com/spf13/viper和https://github.com/zpatrick/go-config是非常好的配置文件库。

我已经开始使用Gcfg,它使用类似ini的文件。它很简单——如果你想要一些简单的东西,这是一个很好的选择。

下面是我目前使用的加载代码,它有默认设置,并允许命令行标志(未显示)覆盖我的一些配置:

package util

import (
    "code.google.com/p/gcfg"
)

type Config struct {
    Port int
    Verbose bool
    AccessLog string
    ErrorLog string
    DbDriver string
    DbConnection string
    DbTblPrefix string
}

type configFile struct {
    Server Config
}

const defaultConfig = `
    [server]
    port = 8000
    verbose = false
    accessLog = -
    errorLog  = -
    dbDriver     = mysql
    dbConnection = testuser:TestPasswd9@/test
    dbTblPrefix  =
`

func LoadConfiguration(cfgFile string, port int, verbose bool) Config {
    var err error
    var cfg configFile

    if cfgFile != "" {
        err = gcfg.ReadFileInto(&cfg, cfgFile)
    } else {
        err = gcfg.ReadStringInto(&cfg, defaultConfig)
    }

    PanicOnError(err)

    if port != 0 {
        cfg.Server.Port = port
    }
    if verbose {
        cfg.Server.Verbose = true
    }

    return cfg.Server
}

看看贡菲

// 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格式非常适合我。的 标准库提供了缩进写入数据结构的方法,因此它是相当 可读。

看看这条高朗坚果线。

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]

像本文一样使用toml读取配置文件