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