将嵌套配置 Yaml 映射到结构

问题描述 投票:0回答:4

我是新手,我正在使用 viper 加载我的所有配置。我目前拥有的是 YAML,如下所示:

 countryQueries:
  sg:
    - qtype: gmap
      qplacetype: postal_code
    - qtype: gmap
      qplacetype: address
    - qtype: geocode
      qplacetype: street_address

  hk:
    - qtype: gmap
      qplacetype: postal_code
    - qtype: gmap
      qplacetype: address
    - qtype: geocode
      qplacetype: street_address

请注意,国家/地区代码是动态的。可以随时为任何国家/地区添加它们。我如何将其映射到从技术上讲我可以做的结构:

for _, query := range countryQueries["sg"] { }

我尝试通过循环来自己构建它,但我被困在这里:

for country, queries := range viper.GetStringMap("countryQueries") {
    // i cant seem to do anything with queries, which i wish to loop it
    for _,query := range queries {} // error here
}
go struct config viper-go
4个回答
8
投票

完成一些阅读后,意识到 viper 有自己的解组功能,效果很好https://github.com/spf13/viper#unmarshaling

这就是我所做的

type Configuration struct {
    Countries map[string][]CountryQuery `mapstructure:"countryQueries"`
}

type CountryQuery struct {
    QType      string
    QPlaceType string
}

func BuildConfig() {
    viper.SetConfigName("configFileName")
    viper.AddConfigPath("./config")
    err := viper.ReadInConfig()
    if err != nil {
        panic(fmt.Errorf("Error config file: %s \n", err))
    }

    var config Configuration

    err = viper.Unmarshal(&config)
    if err != nil {
        panic(fmt.Errorf("Unable to decode Config: %s \n", err))
    }
}

1
投票

这里有一些使用 go-yaml 的简单代码:

package main

import (
    "fmt"
    "gopkg.in/yaml.v2"
    "log"
)

var data = `
countryQueries:
  sg:
    - qtype: gmap
      qplacetype: postal_code
    - qtype: gmap
      qplacetype: address
    - qtype: geocode
      qplacetype: street_address

  hk:
    - qtype: gmap
      qplacetype: postal_code
    - qtype: gmap
      qplacetype: address
    - qtype: geocode
      qplacetype: street_address
`

func main() {
    m := make(map[interface{}]interface{})

    err := yaml.Unmarshal([]byte(data), &m)
    if err != nil {
        log.Fatalf("error: %v", err)
    }

    fmt.Printf("%v\n", m)
}

1
投票

如果您希望将

yaml
结构映射到严格的 golang
struct
,您可以使用 mapstruct 库来映射每个国家/地区下的嵌套键/值对。

例如:

package main

import (
    "github.com/spf13/viper"
    "github.com/mitchellh/mapstructure"
    "fmt"
    "log"
)

type CountryConfig struct {
    Qtype string
    Qplacetype string
}
type QueryConfig struct {
    CountryQueries map[string][]CountryConfig;
}
func NewQueryConfig () QueryConfig {
    queryConfig := QueryConfig{}
    queryConfig.CountryQueries = map[string][]CountryConfig{}
    return queryConfig
}
func main() {

    viper.SetConfigName("test")
    viper.AddConfigPath(".")
    err := viper.ReadInConfig()
    queryConfig := NewQueryConfig()
    if err != nil {
        log.Panic("error:", err)
    } else {
        mapstructure.Decode(viper.AllSettings(), &queryConfig)
    }
    for _, config := range queryConfig.CountryQueries["sg"] {

        fmt.Println("qtype:", config.Qtype, "qplacetype:", config.Qplacetype)
    }
}

0
投票

您可以使用此包https://github.com/go-yaml/yaml在Go中序列化/反序列化YAML。

© www.soinside.com 2019 - 2024. All rights reserved.