我注意到,当 viper 尝试解组为结构时,这可能是一个错误。为了更好地解释它,请考虑一下:
我有一个如下的cli命令
dd-cli submit-bug --name "Bug 1" --tag reason1 --tag reason2
这是我的命令行源代码
package cmd
import (
"fmt"
"github.com/spf13/viper"
"github.com/spf13/cobra"
)
// SubmitBugOpts is a set of flags being exposed by this Deploy command
type SubmitBugOpts struct {
Name string `mapstructure:"bug-name"`
ReasonTags []string `mapstructure:"tags"`
}
var (
submitBugOpts = SubmitBugOpts{}
)
func submitBugRun(cmd *cobra.Command, args []string) {
fmt.Printf("Bug Name is %+v\n", submitBugOpts.Name)
fmt.Printf("List of tags is %+v\n", submitBugOpts.ReasonTags)
fmt.Printf("Length of tags is %d\n", len(submitBugOpts.ReasonTags))
for index, el := range submitBugOpts.ReasonTags {
fmt.Printf("tag[%d] = %s\n", index, el)
}
}
var submitBugCmd = &cobra.Command{
Use: "submit-bug",
Short: "Deploy/Install a helm chart to Kubernetes cluster",
Run: submitBugRun,
PreRun: func(cmd *cobra.Command, args []string) {
pFlags := cmd.PersistentFlags()
viper.BindPFlag("bug-name", pFlags.Lookup("name"))
viper.BindPFlag("tags", pFlags.Lookup("tag"))
fmt.Printf("Viper all setting value: %+v\n", viper.AllSettings())
fmt.Printf("Before unmarshall: %+v\n", submitBugOpts)
viper.Unmarshal(&submitBugOpts)
fmt.Printf("After unmarshall: %+v\n", submitBugOpts)
},
}
func init() {
rootCmd.AddCommand(submitBugCmd)
pFlags := submitBugCmd.PersistentFlags()
pFlags.StringVar(&submitBugOpts.Name, "name", "", "the bug name")
pFlags.StringArrayVar(&submitBugOpts.ReasonTags, "tag", nil, "the bug's reason tag. You can define it multiple times")
submitBugCmd.MarkPersistentFlagRequired("name")
submitBugCmd.MarkPersistentFlagRequired("tag")
}
我运行这个命令:
dd-cli submit-bug --name "Bug 1" --tag reason1 --tag reason2
输出如下
Viper all setting value: map[bug-name:Bug 1 tags:[reason1,reason2]]
Before unmarshall: {Name:Bug 1 ReasonTags:[reason1 reason2]}
After unmarshall: {Name:Bug 1 ReasonTags:[[reason1 reason2]]}
Bug Name is Bug 1
List of tags is [[reason1 reason2]]
Length of tags is 2
tag[0] = [reason1
tag[1] = reason2]
我希望viper.Unmarshall()
将正确地省略[
for submitBugOpts.ReasonTags [0]
并省略]
for submitBugOpts.ReasonTags[1]
。所以 submitBugOpts.ReasonTags 的期望值不包含任何[
and ]
。
任何指针如何解决这个问题?我已经在 viper repo 上提交了这个问题:https ://github.com/spf13/viper/issues/527 。但是,我要问的是,以防万一你们也知道如何处理这个问题。