发布
社区首页 >问答首页 >戈朗:如何用蛇而不是眼镜蛇来支持cli params,env和config文件?

戈朗:如何用蛇而不是眼镜蛇来支持cli params,env和config文件?
EN

Stack Overflow用户
提问于 2022-01-11 20:13:24
回答 2查看 1.2K关注 0票数 1

我正试图编写一个只有一个命令的应用程序,因此,我想我可以跳过眼镜蛇。

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

  • 命令行params
  • env vars
  • 配置文件

我用的是毒蛇,但我无法用它来读我的cli params。

代码语言:javascript
代码运行次数:0
复制
  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)
  }

但我从来没有让那些人进入建筑。在v之前打印Unmarshal没有显示我提供的任何cli参数。

我遗漏了什么?我需要用眼镜蛇做这个吗?还是必须手动将每个标记(例如fs.String(pathKey, defaultPath, "Default path") )分配给配置结构?

EN

回答 2

Stack Overflow用户

发布于 2022-01-11 20:50:54

为了子孙后代,我想我发现了一个问题:

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

代码语言:javascript
代码运行次数:0
复制
const (
  pathKey = "path"
  wordsKey = "words"
  logLevelKey = "logLevel"
)

type conf struct {
   Path string `json:"path"`
   Words []string `json:"words"`
   LogLevel string `json:"logLevel"`
}
票数 1
EN

Stack Overflow用户

发布于 2022-01-11 21:57:58

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

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70672896

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档