1
眼鏡蛇和毒蛇的文檔令我困惑。我做了cobra init fooproject
,然後在項目目錄中我做了cobra add bar
。我有一個名爲foo
的PersistentFlag
,這裏是root
命令的init函數。爲什麼眼鏡蛇不能讀取我的配置文件
func Execute() {
if err := RootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(-1)
}
fmt.Println(cfgFile)
fmt.Println("fooString is: ", fooString)
}
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/.fooproject.yaml)")
RootCmd.PersistentFlags().StringVar(&fooString, "foo", "", "loaded from config")
viper.BindPFlag("foo", RootCmd.PersistentFlags().Lookup("foo"))
// 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")
}
我的配置文件看起來像這樣...
---
foo: aFooString
,當我打電話go run main.go
我看到這個...
A longer description that spans multiple lines and likely contains
examples and usage of using your application. For example:
Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.
Usage:
fooproject [command]
Available Commands:
bar A brief description of your command
help Help about any command
Flags:
--config string config file (default is $HOME/.fooproject.yaml)
--foo string loaded from config
-h, --help help for fooproject
-t, --toggle Help message for toggle
Use "fooproject [command] --help" for more information about a command.
fooString is:
當我打電話go run main.go bar
我看到這個.. 。
Using config file: my/gopath/github.com/user/fooproject/.fooproject.yaml
bar called
fooString is:
所以它使用的是配置文件,但它們中的一個似乎都沒有讀它,也許我誤解了眼鏡蛇和毒蛇的工作方式,有什麼想法?
這種方法很有效,但我認爲這個問題指向了一個我不明白的問題: OP使用'StringVar'而不是'StringP'來獲取傳遞給字符串指針的值它。連接在一起的Cobra&Viper似乎不會將值傳播到那些傳遞的值指針中。 如果有人可以提供一個指示器如何使這項工作,隨時張貼另一個答案。 – Ralf