doujia5863 2018-04-28 04:26
浏览 55
已采纳

带有毒蛇的动态组名

I'm trying to get some groups from the config, which names are not known (will get more later on).

I'm new to golang and struggling a bit. I'm using Viper, because of its support for yaml, json and 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"
                }
            ]
        }
    }
}

and the source:

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
", conf)
}

I have no idea how to cycle through the customers.

I have tried this one already (converted from go-toml to viper), but it didn't work as expected:

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条回答 默认 最新

  • dqo58772 2018-04-28 18:49
    关注

    I started down the road of answering your initial question but it is so cumbersome and probably not what you actually want.

    Your code as you've pasted it has a bunch of errors in it so instead let me offer a simpler solution like I was talking about in my comment.

    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)
    }
    

    If you run this code with your JSON config file (named config) it returns the following output:

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

    And here it is reformatted as it would be written if you were creating this whole structure in code:

     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"}}},
        },
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类