美文网首页GolangGo
Go - 必可不少的配置参数

Go - 必可不少的配置参数

作者: 红薯爱帅 | 来源:发表于2023-04-21 18:29 被阅读0次

1. 概述

通过修改配置参数,我们可以将软件部署到不同环境,也可以使之有不同的行为,大大方便软件的使用与流行。
在golang中,读取配置参数的package有很多,经过对比分析,github.com/spf13/viper的功能最全,且更加可靠。

2. What‘s Viper

Viper is a complete configuration solution for Go applications including 12-Factor apps. It is designed to work within an application, and can handle all types of configuration needs and formats. It supports:

  • setting defaults
  • reading from INI, JSON, TOML, YAML, HCL, envfile and Java properties config files
  • live watching and re-reading of config files (optional)
  • reading from environment variables
  • reading from remote config systems (etcd or Consul), and watching changes
  • reading from command line flags
  • reading from buffer
  • setting explicit values

Viper can be thought of as a registry for all of your applications configuration needs.

spf13/viper: Go configuration with fangs (github.com)

3. 需求分析

根据项目的使用场景,选择ini作为配置文件存储格式,支持两种配置方法:

  • ini配置文件,保存全部配置参数,支持参数注释参数分组默认值
  • 环境变量environment variables,通过section.key=value的方式,覆盖ini中[section]组的key参数值

以后也可以考虑增加命令行参数的支持,优先级最高。Viper同样支持。
为什么不采用yml、toml、json、xml配置,多层级的参数设置,不利于环境变量的设置。

4. 实现与介绍

介绍

  • 配置文件的key,例如RunMode,大小写不敏感
  • 环境变量的设置,须env SERVER.HTTPPORT=12345 go run main.go,注意:key必须全部大写
  • 另外,对于环境变量的使用,需要手动更新相应参数的value,我认为是viper的bug,参考更多
viper.Set(k, os.ExpandEnv(v))

代码实现

  • conf/config.ini
[server]
#debug or release
RunMode = debug
HttpPort = 9898
ReadTimeout = 60s
WriteTimeout = 60s
  • settings/settings.go
package settings

import (
    "fmt"
    "github.com/spf13/viper"
    "log"
    "os"
    "time"
)

type Server struct {
    RunMode      string
    HttpPort     int
    ReadTimeout  time.Duration
    WriteTimeout time.Duration
}

var ServerSettings = &Server{}

// Setup initialize the configuration instance
func Setup() {
    viper.SetConfigName("config")
    viper.AddConfigPath("conf")
    viper.AutomaticEnv()

    if err := viper.ReadInConfig(); err != nil {
        panic(err)
    }

    // https://github.com/spf13/viper/issues/761
    // env SERVER.HTTPPORT=12345 go run main.go
    for _, k := range viper.AllKeys() {
        v := viper.GetString(k)
        viper.Set(k, os.ExpandEnv(v))
    }

    mapTo("server", ServerSettings)
}

// mapTo map section
func mapTo(section string, v interface{}) {
    err := viper.UnmarshalKey(section, v)
    if err != nil {
        log.Fatalf("Setting MapTo %s err: %v", section, err)
    }
}

5. 后记

Viper的功能很强大,还支持设置默认值,例如

viper.SetDefault("ContentDir", "content")
viper.SetDefault("LayoutDir", "layouts")
viper.SetDefault("Taxonomies", map[string]string{"tag": "tags", "category": "categories"})

不过,参数很多的话,这样one by one设置,感觉很拉。能否通过struct tag实现,效果会好很多。

另外,支持监听配置文件的更改,并实时读取和更新配置参数。对于在裸机上部署的软件,还是挺管用的。

// refresh env in real time
viper.OnConfigChange(func(e fsnotify.Event) {
    viper.ReadInConfig()
    RabbitmqUrl = viper.GetString("RABBITMQ_URL")
})
viper.WatchConfig()

时间有限,Viper的一些高级功能还没来得及尝试,有机会再试一试,还挺有意思。

相关文章

网友评论

    本文标题:Go - 必可不少的配置参数

    本文链接:https://www.haomeiwen.com/subject/wofnddtx.html