如何在 Go 中处理配置 [英] How to handle configuration in Go

查看:35
本文介绍了如何在 Go 中处理配置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Go 编程的新手,我想知道:处理 Go 程序的配置参数的首选方法是什么(人们可能会使用属性文件或ini 文件,在其他情况下)?

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)?

推荐答案

JSON 格式为我工作得很好.这标准库提供了编写缩进数据结构的方法,所以它是相当可读.

The JSON format worked for me quite well. The standard library offers methods to write the data structure indented, so it is quite readable.

另见这个 golang-nuts 主题.

JSON 的好处是解析和人类可读/可编辑相当简单同时为列表和映射提供语义(这会变得非常方便),许多 ini 类型的配置解析器并非如此.

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.

示例用法:

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]

这篇关于如何在 Go 中处理配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆