【发布时间】:2019-10-20 15:39:51
【问题描述】:
我正在尝试在 Go 中开发一个应用程序,它接受命令行上的输入作为键值对字符串。为此,我使用 Cobra 库中的 StrngToStringVar。
我还使用 Viper 将这些标志绑定到配置,但是无论我输入什么值,我似乎都无法从 Viper 获取它。
这是代码
package main
import (
"fmt"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"github.com/davecgh/go-spew/spew"
)
func main() {
var items map[string]string
var name string
rootCmd := &cobra.Command{
Use: "cobra",
Short: "Test options on the command line",
Long: ``,
Run: func(ccmd *cobra.Command, args []string) {
spew.Dump(viper.GetString("name"))
spew.Println("")
fmt.Println("GetStringMap")
spew.Dump(viper.GetStringMap("items"))
fmt.Println("")
fmt.Println("GetStringMapString")
spew.Dump(viper.GetStringMapString("items"))
},
}
rootCmd.Flags().StringVar(&name, "name", "", "Name of the list")
rootCmd.Flags().StringToStringVar(&items, "item", nil, "Map stating the items to be included")
viper.BindPFlag("name", rootCmd.Flags().Lookup("name"))
viper.BindPFlag("items", rootCmd.Flags().Lookup("item"))
rootCmd.Execute()
}
如果我使用命令 go run .\main.go --item shopping=apple,banana --name foobar 运行它,我会得到以下结果
(string) (len=6) "foobar"
GetStringMap
(map[string]interface {}) {
}
GetStringMapString
(map[string]string) {
}
可以看出,即使我正确设置了输入(我相信),他的输出也不包含任何项目。我一直在尝试使用 PR https://github.com/spf13/pflag/pull/133 来弄清楚如何做到这一点,但我没有任何运气。
我想知道绑定是否不正确,但是我在其他项目中成功使用过CObra,所以我对如何引用来自Cobra 生成的map[string]string 缺乏了解。
【问题讨论】:
-
您是否尝试使用变量
items和names作为包变量