带有viper的动态组名

时间:2018-04-28 04:26:31

标签: go

我试图从配置中获取一些组,这些组名称未知(稍后会更多)。

我是golang的新手并且有点挣扎。我使用的是Viper,因为它支持yaml,json和toml。

json config:

{
    "database": {
        "db": "mydb",
        "host": "localhost",
        "pass": "mypassword",
        "port": 3306,
        "user": "username"
    },
    "customers": {
        "company_one": {
            "address": "66 Great Queen St, London WC2B 5BX, UK",
            "contacts": [
                {
                    "email": "joe.doe@company-one.local",
                    "name": "Joe Doe"
                },
                {
                    "email": "jane.doe@company-one.local",
                    "name": "Jane Doe"
                }
            ]
        },
        "company_two": {
            "address": "Irish Town Pl, Gibraltar GX11 1AA, Gibraltar",
            "contacts": [
                {
                    "email": "lucky.luke@second-company.local",
                    "name": "Lucky Luke"
                }
            ]
        }
    }
}

和来源:

package main

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

type Config struct {
    database Database
    customers Customer
}

type Database struct {
    host string
    port uint16
    user string
    pass string
    db string
}

type Customer struct {
    company Company
}

type Company struct {
    contacts Contact
    address string
}

type Contact struct {
    name string
    email string
}

func main() {
    viper.SetConfigName("a")
    viper.AddConfigPath(".")
    if err := viper.ReadInConfig(); err != nil {
        log.Fatal("Unable to read config file", err)
    }
    var conf Config
    database := viper.GetStringMap("database")
    for key, i := range database {
        switch key {
        case "host":
            conf.database.host = i.(string)
        case "port":
            conf.database.port = i.(uint16)
        case "user":
            conf.database.user = i.(string)
        case "pass":
            conf.database.pass = i.(string)
        case "db":
            conf.database.db = i.(string)
        }
    }
    fmt.Printf("%v\n", conf)
}

我不知道如何循环顾客。

我已经尝试过这个(从go-toml转换为viper),但它没有像预期的那样工作:

var contMap = map[string]Contacts

cust := config.Get("customers")

for _, c := range cust.Keys() {
    sub := cust.Get(c).([]interface{})
    for _,d := range sub{
        address := d.([]interface{})[0].(string)
        hostMap[host] = Contacts{
            email: email,
            name: name,
        }
    }
    log.Printf("Customers: %s contact: %q", c, sub)
}

1 个答案:

答案 0 :(得分:0)

我开始回答你最初的问题,但它太麻烦了,可能不是你真正想要的。

你粘贴的代码中有很多错误,所以让我提供一个比我在评论中谈论的更简单的解决方案。

package main

import (
    "log"

    "github.com/spf13/viper"
)

type Config struct {
    Database  Database           `mapstructure:"database"`
    Customers map[string]Company `mapstructure:"customers"`
}

type Database struct {
    Host string `mapstructure:"host"`
    Port uint16 `mapstructure:"port"`
    User string `mapstructure:"user"`
    Pass string `mapstructure:"pass"`
    Db   string `mapstructure:"db"`
}

type Company struct {
    Address  string    `mapstructure:"address"`
    Contacts []Contact `mapstructure:"contacts"`
}

type Contact struct {
    Name  string `mapstructure:"name"`
    Email string `mapstructure:"email"`
}

func main() {
    viper.SetConfigName("config")
    viper.AddConfigPath(".")
    if err := viper.ReadInConfig(); err != nil {
        log.Fatal("Unable to read config file", err)
    }
    var conf Config
    err := viper.Unmarshal(&conf)
    if err != nil {
        panic(err)
    }

    log.Printf("%#v", conf)
}

如果使用JSON配置文件(名为config)运行此代码,则返回以下输出:

  

2018/04/28 14:47:54   main.Config {数据库:main.Database {主机:“localhost”,端口:0xcea,   用户:“用户名”,传递:“mypassword”,Db:“mydb”},   客户:地图[字符串] main.Company { “company_two”:main.Company {地址:“爱尔兰   Town Pl,Gibraltar GX11 1AA,直布罗陀“,   联系人:[] main.Contact {main.Contact {名称:“Lucky Luke”,   电子邮件: “lucky.luke@second-company.local”}}},   “company_one”:main.Company {地址:“66 Great Queen St,London WC2B   5BX,UK“,联系方式:[] main.Contact {main.Contact {Name:”Joe Doe“,   电子邮件:“joe.doe@company-one.local”},main.Contact {姓名:“Jane Doe”,   电子邮件: “jane.doe@company-one.local”}}}}}

在这里它被重新格式化,因为如果你在代码中创建整个结构将会被写入:

 Config{
    Database{
        Host: "localhost",
        Port: 0xcea,
        User: "username",
        Pass: "mypassword",
        Db:   "mydb"},
    Customers: map[string]Company{
        "company_two": Company{Address: "Irish Town Pl, Gibraltar GX11 1AA, Gibraltar",
            Contacts: []Contact{
                Contact{Name: "Lucky Luke", Email: "lucky.luke@second-company.local"}}},
        "company_one": Company{Address: "66 Great Queen St, London WC2B 5BX, UK",
            Contacts: []Contact{
                Contact{Name: "Joe Doe", Email: "joe.doe@company-one.local"},
                Contact{Name: "Jane Doe", Email: "jane.doe@company-one.local"}}},
    },
}