drfu29983 2017-03-12 11:56
浏览 68
已采纳

使用Viper语言处理界面

I am building a little app using Viper and Cobra. At the moment, I have a yaml file like this:

hosts:
  - name: host1
    port: 90
    key: my_key
  - name: host2
    port: 90
    key: prompt

And I've read in the config file using Viper.

When I run viper.Get("hosts") it returns an interface (or a slice of interfaces?). This is the data structure I end up with:

([]interface {}) (len=2 cap=2) {
 (map[interface {}]interface {}) (len=3) {
  (string) (len=4) "name": (string) (len=20) "host1",
  (string) (len=4) "port": (int) 90,
  (string) (len=3) "key": (string) (len=6) "my_key"
 },
 (map[interface {}]interface {}) (len=3) {
  (string) (len=3) "key": (string) (len=6) "prompt",
  (string) (len=4) "name": (string) (len=20) "host2",
  (string) (len=4) "port": (int) 90
 }
}

What I'd like to do here is loop over each of the array elements and perform an operation using the values of name, port and key.

I'm completely new to interfaces in Golang, so this isn't very clear, and the literature on this is extremely confusing :(

Any help is appreciated.

  • 写回答

1条回答 默认 最新

  • dousonghs58612 2017-03-12 14:34
    关注

    By defining the configuration file type and using viper.Unmarshal you can cast the interface to specific type you need. Here is an example:

    main.go

    package main
    
    import (
        "fmt"
    
        "github.com/spf13/viper"
    )
    
    type Host struct {
        Name string
        Port int
        Key  string
    }
    
    type Config struct {
        Hosts []Host
    }
    
    func main() {
        viper.AddConfigPath("./")
        viper.SetConfigName("test")
        viper.ReadInConfig()
        var config Config
        err := viper.Unmarshal(&config)
        if err != nil {
            panic("Unable to unmarshal config")
        }
        for _, h := range config.Hosts {
            fmt.Printf("Name: %s, Port: %d, Key: %s
    ", h.Name, h.Port, h.Key)
        }
    }
    

    test.yml

    hosts:
      - name: host1
        port: 90
        key: my_key
      - name: host2
        port: 90
        key: prompt
    

    Run:

    $ go run main.go
    Name: host1, Port: 90, Key: my_key
    Name: host2, Port: 90, Key: prompt
    

    If you want to decode only some keys, not the entire configuration file, use viper.UnmarshalKey.

    main.go

    package main
    
    import (
        "fmt"
    
        "github.com/spf13/viper"
    )
    
    type Host struct {
        Name string
        Port int
        Key  string
    }
    
    func main() {
        viper.AddConfigPath("./")
        viper.SetConfigName("test")
        viper.ReadInConfig()
        var hosts []Host
        err := viper.UnmarshalKey("hosts", &hosts)
        if err != nil {
            panic("Unable to unmarshal hosts")
        }
        for _, h := range hosts {
            fmt.Printf("Name: %s, Port: %d, Key: %s
    ", h.Name, h.Port, h.Key)
        }
    }
    

    Run:

    $ go run main.go
    Name: host1, Port: 90, Key: my_key
    Name: host2, Port: 90, Key: prompt
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 对于知识的学以致用的解释
  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败