the*_*ber 281 configuration-files go
我是Go编程的新手,我想知道:处理Go程序的配置参数的首选方法是什么(在其他环境中可能使用属性文件或ini文件的那种东西)?
nem*_*emo 241
该JSON格式为我工作得很好.标准库提供了以缩进方式编写数据结构的方法,因此它非常易读.
JSON的好处是,在为列表和映射提供语义(这可能变得非常方便)时,解析和人类可读/可编辑相当简单,而许多ini类型的配置解析器则不然.
用法示例:
conf.json:
{
"Users": ["UserA","UserB"],
"Groups": ["GroupA"]
}
Run Code Online (Sandbox Code Playgroud)
程序读取配置
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]
Run Code Online (Sandbox Code Playgroud)
Bur*_*hi5 94
另一种选择是使用TOML,这是由Tom Preston-Werner创建的类似INI的格式.我为它构建了一个Go解析器,经过了广泛的测试.您可以像在此处提出的其他选项一样使用它.例如,如果您有此TOML数据something.toml
Age = 198
Cats = [ "Cauchy", "Plato" ]
Pi = 3.14
Perfection = [ 6, 28, 496, 8128 ]
DOB = 1987-07-05T05:45:00Z
Run Code Online (Sandbox Code Playgroud)
然后你可以把它加载到你的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
}
Run Code Online (Sandbox Code Playgroud)
Ask*_*sen 44
我通常使用JSON来处理更复杂的数据结构.缺点是你很容易得到一堆代码来告诉用户错误的位置,各种边缘情况以及什么不是.
对于基本配置(api键,端口号,......)我对gcfg包非常好运.它基于git配置格式.
从文档:
示例配置:
; Comment line
[section]
name = value # Another comment
flag # implicit value for bool is true
Run Code Online (Sandbox Code Playgroud)
结构:
type Config struct {
Section struct {
Name string
Flag bool
}
}
Run Code Online (Sandbox Code Playgroud)
并且代码需要阅读它:
var cfg Config
err := gcfg.ReadFileInto(&cfg, "myconfig.gcfg")
Run Code Online (Sandbox Code Playgroud)
它还支持切片值,因此您可以允许多次指定键以及其他类似功能.
val*_*ala 39
标准手旗有以下好处:
标准go标志的唯一缺点是 - 当您的应用程序中使用的标志数量变得太大时,管理问题.
Iniflags优雅地解决了这个问题:只需修改主包中的两行,它就会神奇地获得从ini文件中读取标志值的支持.可以通过在命令行中传递新值来覆盖ini文件中的标志.
有关详细信息,另请参阅https://groups.google.com/forum/#!topic/golang-nuts/TByzyPgoAQE.
Ric*_*777 12
我已经开始使用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
}
Run Code Online (Sandbox Code Playgroud)
看看gonfig
// 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)
Run Code Online (Sandbox Code Playgroud)
https://github.com/spf13/viper和https://github.com/zpatrick/go-config是一个非常好的配置文件库.
我在golang中编写了一个简单的ini配置库。
goroutine安全,易于使用
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)
}
}
Run Code Online (Sandbox Code Playgroud)
==================更新=======================
最近,我需要具有部分支持的INI解析器,并且编写了一个简单的程序包:
github.com/c4pt0r/cfg
Run Code Online (Sandbox Code Playgroud)
您可以像使用“标志”包那样解析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)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
150427 次 |
| 最近记录: |