Skip to content

Instantly share code, notes, and snippets.

@abraithwaite
Created November 8, 2017 22:28
Show Gist options
  • Save abraithwaite/43a687090142b0dc85c2aa68df9c8950 to your computer and use it in GitHub Desktop.
Save abraithwaite/43a687090142b0dc85c2aa68df9c8950 to your computer and use it in GitHub Desktop.
Neat way to do configuration in Golang
package main
import (
"encoding/json"
"errors"
"fmt"
"reflect"
"github.com/tidwall/gjson"
)
var v string = `
[
{ "Type": "Alpha", "Omega": "Blah" },
{ "Type": "Beta", "Gamma": "Hah" }
]
`
var types map[string]reflect.Type = map[string]reflect.Type{
"Alpha": reflect.TypeOf(Alpha{}),
"Beta": reflect.TypeOf(Beta{}),
}
type Alpha struct {
Omega string
}
type Beta struct {
Gamma string
}
func main() {
var opts []json.RawMessage
err := json.Unmarshal([]byte(v), &opts)
if err != nil {
panic(err)
}
for _, o := range opts {
x, err := Unmarshal(o)
if err != nil {
panic(err)
}
switch v := x.(type) {
case *Alpha:
fmt.Printf("Alpha: %v\n", v)
case *Beta:
fmt.Printf("Beta: %v\n", v)
}
}
}
func Unmarshal(raw json.RawMessage) (interface{}, error) {
x := gjson.Get(string(raw), "Type")
if typ, ok := types[x.Str]; ok {
str := reflect.New(typ).Interface()
err := json.Unmarshal([]byte(raw), &str)
return str, err
}
return nil, errors.New("unknown type")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment