如何在Go中处理配置 [英] How to handle configuration in Go
问题描述
我是Go编程的新手,我想知道:处理Go程序的配置参数的首选方法是什么(可以使用属性文件或 ini 文件,在其他上下文中)?
JSON 格式对我很有帮助。
标准库提供了缩写数据结构的方法,所以它可以读取
。 此golang-nuts线程。
JSON的好处在于,它为解析和人类可读/可编辑的
提供了相当简单的同时提供了列表和映射的语义(这可以变得非常方便),而
不是这种情况许多ini型配置解析器。
示例用法:
$ b conf.json :
{
Users:[UserA,UserB],
Groups :[GroupA]
}
程序读取配置
import(
encoding / json
os
fmt
)
类型配置struct {
用户[]字符串
组[]字符串
}
文件, _:= os.Open(conf.json)
推迟file.Close()
解码器:= json.NewDecoder(文件)
配置:=配置{}
err:= decoder.Decode(& configuration)
if err!= nil {
fmt.Println(error:,err)
}
fmt.Println(configuration .Users)//输出:[UserA,UserB]
I'm new at Go programming, and I'm wondering: what is the preferred way to handle configuration parameters for a Go program (the kind of stuff one might use properties files or ini files for, in other contexts)?
The JSON format worked for me quite well. The standard library offers methods to write the data structure indented, so it is quite readable.
See also this golang-nuts thread.
The benefits of JSON are that it is fairly simple to parse and human readable/editable while offering semantics for lists and mappings (which can become quite handy), which is not the case with many ini-type config parsers.
Example usage:
conf.json:
{
"Users": ["UserA","UserB"],
"Groups": ["GroupA"]
}
Program to read the configuration
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]
这篇关于如何在Go中处理配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!