亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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 關注
  • 163 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號