我有以下配置模型:type Config struct { Project []Project `mapstructure:"project"`}type Project struct { Name string `mapstructure:"name"`}我希望能夠使用配置文件以及命令行上的選項對此進行配置。我知道如何通過以正確的格式傳遞它然后取消編組來執行配置文件。但是,我無法弄清楚該怎么做的是使用Cobra在命令行上設置項目名稱,然后讓Viper將該值綁定為Project數組中的第一項。以下是我放在一起的簡單程序,以顯示我遇到的問題:package mainimport ( "fmt" "log" "github.com/spf13/cobra" "github.com/spf13/viper")type Config struct { Project []Project `mapstructure:"project"` Name string `mapstructure:"name"`}type Project struct { Name string `mapstructure:"name"`}var ( config Config rootCmd = &cobra.Command{ Use: "rjsdummy", Short: "Dummy app to understand Viper BindPFlags", Long: "", PersistentPreRun: preRun, Run: executeRun, })func init() { var name string var project_name string cobra.OnInitialize() // configure the flags on the command line rootCmd.Flags().StringVarP(&name, "name", "n", "", "Your name") rootCmd.Flags().StringVarP(&project_name, "project", "p", "", "Project name") // bind the flags to the configuration viper.BindPFlag("name", rootCmd.Flags().Lookup(("name"))) viper.BindPFlag("project.0.name", rootCmd.Flags().Lookup(("project")))}func preRun(ccmd *cobra.Command, args []string) { err := viper.Unmarshal(&config) if err != nil { log.Fatalf("Unable to read Viper options into configuration: %v", err) }}func executeRun(ccmd *cobra.Command, args []string) { fmt.Printf("Your name: %s\n", config.Name) fmt.Printf("Project name: %s\n", config.Project[0].Name)}func main() { rootCmd.Execute()}當我使用命令運行此命令時,我得到以下輸出:go run .\binding.go -n Russell -p Turtle所以我知道這條線不起作用。如果我將其更改為,我將獲得堆棧跟蹤。問題是我如何添加這個(和其他屬性)作為復雜對象數組中的第一項?我可以有第二個Viper來讀取另一個對象,然后添加到主配置中,還是有另一種方法?viper.BindPFlag("project.0.name", rootCmd.Flags().Lookup(("project")))project[0].name
1 回答

斯蒂芬大帝
TA貢獻1827條經驗 獲得超8個贊
在玩了這個問題之后,我有了答案。
即使我已經設置了配置,以便它有一個切片項目,Viper也足夠聰明地解決了這個問題。Project []Project
因此,要將項目名稱綁定到切片的第一個元素,就像使用:
viper.BindPFlag("project.name", runCmd.Flags().Lookup("name"))
不需要索引。但是,我可以打印以下值:
fmt.Println(Config.Project[0].Name)
我過度思考這個
- 1 回答
- 0 關注
- 70 瀏覽
添加回答
舉報
0/150
提交
取消