处理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)
Viper是一个golang配置管理系统,可以使用JSON、YAML和TOML。看起来很有趣。
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,这是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)
}