【问题标题】:golang: how to support cli params, env vars and config file with viper but no cobra?golang:如何使用 viper 但没有 cobra 支持 cli 参数、环境变量和配置文件?
【发布时间】:2022-01-14 06:27:01
【问题描述】:

我正在尝试编写一个只有一个命令的应用程序,因此,我想我可能会跳过 Cobra。

应用应该能够支持所有类型的配置:

  • 命令行参数
  • 环境变量
  • 配置文件

我正在使用 viper,但我无法让它读取我的 cli 参数。

  v := viper.New()
  viper.SetConfigName("config") 
  viper.AddConfigPath(".")      
  v.SetDefault(pathKey, defaultPath)

  fs := pflag.NewFlagSet("app", pflag.ExitOnError)
  fs.String(pathKey, defaultPath, "Default path")
  fs.StringSlice(wordsKey, []string{""}, "Words")
  fs.String(loglevelKey, "info", "Log level")

  if err := v.BindPFlags(fs); err != nil {
    fmt.Println(err)
    os.Exit(1)
  }
  if err := fs.Parse(os.Args[1:]); err != nil {
    fmt.Println(err)
    os.Exit(1)
  }

  v.AutomaticEnv()

  if err := v.ReadInConfig(); err != nil {
    fmt.Println("no conf file") //ignore, it can be either cli params, or conf file
  }

  var c conf
  if err := v.Unmarshal(&c); err != nil {
    fmt.Println(err)
    os.Exit(1)
  }

但我从来没有将 cli 参数放入 conf 结构中。在Unmarshal 之前打印v 不会显示我提供的任何cli 参数。

我错过了什么?我需要为此使用眼镜蛇吗? 还是我必须分配每个标志集标志,例如fs.String(pathKey, defaultPath, "Default path"),手动配置结构?

【问题讨论】:

    标签: go config viper-go


    【解决方案1】:

    对于后人,我想我找到了问题:

    我的conf 结构没有标志对应的键名。例如设置json:"logLevel" 字段名为DisplayLogLevel 是不够的,必须是:

    const (
      pathKey = "path"
      wordsKey = "words"
      logLevelKey = "logLevel"
    )
    
    type conf struct {
       Path string `json:"path"`
       Words []string `json:"words"`
       LogLevel string `json:"logLevel"`
    }
    

    【讨论】:

      【解决方案2】:

      也许你必须设置配置类型。来自https://github.com/spf13/viper:

      viper.SetConfigType("yaml") // REQUIRED if the config file does not have the extension in the name

      【讨论】:

        猜你喜欢
        • 2017-05-25
        • 2022-12-01
        • 1970-01-01
        • 2019-04-10
        • 2018-04-18
        • 2019-01-16
        • 2020-12-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多