我一直在嘗試通過解組我的 json 文件來提取一些 JSON,但是,我不知道為什么它沒有發(fā)生。我能夠使用viper.AllSettings()但不能通過解組來獲取數(shù)據(jù)。我認(rèn)為我犯了一個(gè)愚蠢的錯(cuò)誤,請(qǐng)分享您的想法。github鏈接是-https: //github.com/parthw/100-days-of-code/tree/main/golang/d6-cobra-viper-continued,代碼如下。main.gopackage mainimport ( "fmt" "example.com/cobra-viper/cmd" "github.com/spf13/viper")// Myconfig exampletype Myconfig struct { username string `mapstructure:"username"`}func main() { cmd.Execute() fmt.Println("I can print this ", viper.AllSettings()) var mc Myconfig if err := viper.Unmarshal(&mc); err != nil { fmt.Println(err) } fmt.Println(mc)}在 cmd 目錄中使用 cobra CLI 生成的代碼:package cmdimport ( "fmt" "os" "github.com/spf13/cobra" homedir "github.com/mitchellh/go-homedir" "github.com/spf13/viper")var ( cfgFile string author string)// Myconfig exampletype Myconfig struct { username string}// rootCmd represents the base command when called without any subcommandsvar rootCmd = &cobra.Command{ Use: "cobra-viper", Short: "A brief description of your application", Long: `A longer description that spans multiple lines and likely containsexamples 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 filesto quickly create a Cobra application.`, // Uncomment the following line if your bare application // has an action associated with it: Run: func(cmd *cobra.Command, args []string) { fmt.Println("Welcome to rootcmd") var mc Myconfig if err := viper.Unmarshal(&mc); err != nil { fmt.Println(err) } fmt.Println(mc) fmt.Println("I can print this ", viper.AllSettings()) },}
1 回答
斯蒂芬大帝
TA貢獻(xiàn)1827條經(jīng)驗(yàn) 獲得超8個(gè)贊
您的問題歸結(jié)為一個(gè)事實(shí),即您的結(jié)構(gòu)中的username字段是否已導(dǎo)出。MyConfig它需要大寫才能“導(dǎo)出”Unmarshal以將值解碼到結(jié)構(gòu)中。
type Myconfig struct {
Username string `mapstructure:"username"
}您可以查看JSON 并處理未導(dǎo)出的字段,以更多地了解json包需要它的原因。
- 1 回答
- 0 關(guān)注
- 262 瀏覽
添加回答
舉報(bào)
0/150
提交
取消
