【问题标题】:How to make config file in Golang elegantly?如何优雅地在 Golang 中制作配置文件?
【发布时间】:2022-01-29 22:01:07
【问题描述】:

我是 Golang 的新手。 我想编写一个程序来管理我的 Redis 实例,以便我可以使用特定的配置文件创建 Redis 连接。但是我不知道如何优雅地为 Redis 实例创建配置文件。

我之前找到了“文本/模板”,这是个好主意吗?

【问题讨论】:

标签: go redis config


【解决方案1】:

这取决于您想要支持这些配置的文件格式。

能够读取大部分格式(从简单的 ini 文件到 JSON 格式)的库是 spf13/viper

Viper 是 Go 应用程序的完整配置解决方案。它被设计为在应用程序中工作以处理所有类型的配置。支持

  • 设置默认值
  • 从 yaml、toml 和 json 配置文件中读取
  • 从环境变量中读取
  • 从远程配置系统(Etcd 或 Consul)读取
  • 从命令行标志读取
  • 设置显式值

【讨论】:

  • 您的 viper 链接已损坏,但该库看起来很酷。 +1 分享
  • @Lander 我修复了链接。
【解决方案2】:

Redis configuration files 具有简单的文本格式。您可以使用 fmt 包生成配置文件:

fmt.Fprintf(w, "pidfile %s\n", pidFile)
fmt.Fprintf(w, "port %d\n", port)

其中wio.Writer 用于输出。

文本/模板包也是一个可行的选择。给定模板

pidfile {{.PidFile}}
port {{.Port}}

你可以执行它

t.Execute(w, map[string]interface{}{
   "PidFile": pidFile,
   "Port": port,
})

【讨论】:

  • 模板很好用。 +1
【解决方案3】:

由于 redis 配置文件的结构非常简单,我建议您查看将 Reader.Comma 分隔符设置为空白的 encoding/csv 包。它允许您轻松读取、解析和写入配置。在我看来,“slaveof {{.Host}} {{.Port}}”作为模板看起来不是很方便。但这肯定是正确的方法。只是口味问题。

【讨论】:

    【解决方案4】:

    如果你想为开发、测试、登台和生产制作配置文件,我建议使用 Go 提供的 // +build 可能性。


    设置你的 Go 程序

    您在 config 包中创建 4 个文件,如下所示:

    src/program/config
                   |
                   |--config_dev.go
                   |--config_test.go
                   |--config_staging.go
                   |--config_prod.go
    

    在配置文件中

    然后在每个文件中,定义用于在go build(或运行,...)过程中使用该文件的标记。

    这意味着例如在 config_dev.go 中:

    // +build dev
    
    package config
    
    // Development ready configuration const based on the build tags.
    const (
        MYSETTINGS = "dev blablabla"
        ISREADY    = false
    )
    

    config_test.go 中,它看起来像:

    // +build test
    
    package config
    
    // Development ready configuration const based on the build tags.
    const (
        MYSETTINGS = "test blablabla"
        ISREADY    = true
    )
    

    注意// +build dev// +build test

    这是您将在构建期间使用的标签,用于告诉您要使用哪个配置文件。

    在任何其他 Go 文件中,您只需调用 config.ISREADY 而无需在文件中导入任何其他 "config"


    构建

    然后要构建您的应用程序,您只需运行:

    go build -tags dev 使用开发配置进行构建

    go build -tags test 使用测试配置进行构建。

    【讨论】:

      【解决方案5】:

      我建议使用一些配置库。我喜欢Viper,因为它是完整的。

      【讨论】:

        猜你喜欢
        • 2019-07-25
        • 1970-01-01
        • 2020-06-10
        • 1970-01-01
        • 2012-03-12
        • 1970-01-01
        • 2022-10-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多