为了账号安全,请及时绑定邮箱和手机立即绑定

cobra go cli 库忽略标志

cobra go cli 库忽略标志

Go
开心每一天1111 2023-08-07 19:11:12
这是来自的一个片段my-tool/cmd/root.gofunc Execute() {    if err := rootCmd.Execute(); err != nil {        fmt.Println(err)        os.Exit(1)    }}func init() {    cobra.OnInitialize(initConfig)    // Here you will define your flags and configuration settings.    // Cobra supports persistent flags, which, if defined here,    // will be global for your application.    rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.my-tool.yaml)")    // Cobra also supports local flags, which will only run    // when this action is called directly.    rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")}// initConfig reads in config file and ENV variables if set.func initConfig() {    if cfgFile != "" {        fmt.Println("Config file set")        // Use config file from the flag.        viper.SetConfigFile(cfgFile)    } else {        fmt.Println("Config file NOT set")        // Find home directory.        home, err := homedir.Dir()        if err != nil {            fmt.Println(err)            os.Exit(1)        }代码是从cobracli 的脚手架过程生成的,即通过~/go/cobra/init my-tool --pkg-name github.com/something/my-tool我试图暂时传递该config标志来检查程序是否正在处理它:▶ go run main.go  --config "test"  但是,尽管我希望该init()函数能够调用cobra.OnInitialize(initConfig)并解析该标志,如行所示:    rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.my-tool.yaml)")最后在声明中看到这两条消息之一if:func initConfig() {    if cfgFile != "" {        fmt.Println("Config file set")        // Use config file from the flag.        viper.SetConfigFile(cfgFile)    } else {        fmt.Println("Config file NOT set")        // Find home directory.        home, err := homedir.Dir()        if err != nil {            fmt.Println(err)            os.Exit(1)        }相反,我得到的只是 root 命令的help消息;这是为什么?编辑:从我看来,通过添加一些打印语句,initConfig()永远不会调用(出于某种原因),即好像cobra.OnInitialize(initConfig)没有执行任何操作。
查看完整描述

1 回答

?
慕慕森

TA贡献1856条经验 获得超17个赞

您需要先指定您的命令


▶ go run main.go "yourcommand" --config "test"


看:


» go run main.go --config "blah"

A longer description that spans multiple lines and likely contains

examples and usage of using your application. For example:

...


» go run main.go preview --config "blah"

Error:  open : no such file or directory

exit status 1


查看完整回答
反对 回复 2023-08-07
  • 1 回答
  • 0 关注
  • 83 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信