首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >无法使用viper进行解组

无法使用viper进行解组
EN

Stack Overflow用户
提问于 2020-11-20 03:35:53
回答 1查看 1.9K关注 0票数 1

我一直试图通过解组我的JSON文件来提取一些json,但我不知道为什么它没有发生。我可以使用viper.AllSettings()获取数据,但不能通过解组获取数据。我想我犯了一个愚蠢的错误,请分享你的想法。github链接是- https://github.com/parthw/100-days-of-code/tree/main/golang/d6-cobra-viper-continued,代码如下。

main.go

代码语言:javascript
运行
复制
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生成的代码:

代码语言:javascript
运行
复制
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())
    },
}

// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
    if err := rootCmd.Execute(); err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
    fmt.Println("I can print this ", viper.AllSettings())
}

func init() {
    cobra.OnInitialize(initConfig)

    // Here you will define your flags and configuration settings.
    // Cobra supports persistent flags, which, if defined here,
    // will be global for your application.

    rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobra-viper.json)")
    //rootCmd.PersistentFlags().StringVar(&author, "author", "YOUR NAME", "Author name for copyright attribution")

    // Cobra also supports local flags, which will only run
    // when this action is called directly.
    //rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
    //viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author"))

}

// initConfig reads in config file and ENV variables if set.
func initConfig() {
    if cfgFile != "" {
        // Use config file from the flag.
        viper.SetConfigFile(cfgFile)
    } else {
        // Find home directory.
        home, err := homedir.Dir()
        if err != nil {
            fmt.Println(err)
            os.Exit(1)
        }

        // Search config in home directory with name ".cobra-viper" (without extension).
        viper.AddConfigPath(home)
        viper.SetConfigName(".cobra-viper")
    }

    viper.AutomaticEnv() // read in environment variables that match

    // If a config file is found, read it in.
    if err := viper.ReadInConfig(); err == nil {
        fmt.Println("Using config file:", viper.ConfigFileUsed())
    }

}

输出:

代码语言:javascript
运行
复制
~/Documents/personal-git/100-days-of-code/golang/d6-cobra-viper-continued(main*) » go run main.go                                                                                   
Using config file: /Users/parth/.cobra-viper.json
Welcome to rootcmd
{}
I can print this  map[username:parth-wadhwa]
I can print this  map[username:parth-wadhwa]
I can print this  map[username:parth-wadhwa]
{}

JSON文件:

代码语言:javascript
运行
复制
~/Documents/personal-git/100-days-of-code/golang/d6-cobra-viper-continued(main*) » cat /Users/parth/.cobra-viper.json                                                              

{
  "username": "parth-wadhwa"
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-11-20 03:55:14

您的问题可以简单地归结为MyConfig结构中的username字段是否被导出。它需要被“导出”,这样Unmarshal才能将值解码为结构。

代码语言:javascript
运行
复制
type Myconfig struct {
    Username string `mapstructure:"username"`
}

您可以查看JSON and dealing with unexported fields以了解json包为什么需要它的更多信息。

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64918795

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档