[英]cobra go cli library ignores flags
這是來自my-tool/cmd/root.go
func 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)
}
代碼由cobra
cli的腳手架過程生成,即通過~/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)
不做任何事情。
您需要先指定您的命令
▶ 運行 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.