我一直在尝试通过解组我的 json 文件来提取一些 JSON,但是,我不知道为什么它没有发生。我能够使用viper.AllSettings()但不能通过解组来获取数据。我认为我犯了一个愚蠢的错误,请分享您的想法。github链接是-https: //github.com/parthw/100-days-of-code/tree/main/golang/d6-cobra-viper-continued,代码如下。
main.go
package main
import (
"fmt"
"example.com/cobra-viper/cmd"
"github.com/spf13/viper"
)
// Myconfig example
type 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 cmd
import (
"fmt"
"os"
"github.com/spf13/cobra"
homedir "github.com/mitchellh/go-homedir"
"github.com/spf13/viper"
)
var (
cfgFile string
author string
)
// Myconfig example
type Myconfig struct {
username string
}
// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
Use: "cobra-viper",
Short: "A brief description of your application",
Long: `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.`,
// 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())
},
}
斯蒂芬大帝
相关分类