关闭 。这个问题需要更加集中。它目前不接受答案。
想改进这个问题? 更新问题,使其仅通过编辑此帖子专注于一个问题。
6年前关闭。
改进这个问题
我是 Go 编程的新手,我想知道:处理 Go 程序的配置参数的首选方法是什么(在其他情况下,可能使用 属性 文件或 ini 文件的那种东西)?
JSON格式非常适合我。标准库提供了编写缩进数据结构的方法,因此可读性很强。
另请参阅[此 golang-nuts 线程](https://groups.google.com/forum/?fromgroups=#!topic/golang- nuts/sAofmg2_lL8)。
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]