必承其重 | 欲带皇冠 2013-05-09 15:41 采纳率: 50%
浏览 355
已采纳

如何处理 Go [关闭]中的配置

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

转载于:https://stackoverflow.com/questions/16465705/how-to-handle-configuration-in-go

  • 写回答

12条回答 默认 最新

  • python小菜 2013-05-09 16:05
    关注

    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]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(11条)

报告相同问题?