Skip to content

Instantly share code, notes, and snippets.

@xealgo
Last active May 10, 2017 21:35
Show Gist options
  • Save xealgo/bda47f6c66cb3c89de54c8beefd6fa93 to your computer and use it in GitHub Desktop.
Save xealgo/bda47f6c66cb3c89de54c8beefd6fa93 to your computer and use it in GitHub Desktop.
Simple struct to map[string]interface{}
package search
import (
"reflect"
"strings"
)
// Build creates a map[string]interface object from a given
// struct based on tags.
func Build(tagName string, model interface{}) map[string]interface{} {
out := map[string]interface{}{}
t := reflect.TypeOf(model)
v := reflect.ValueOf(model)
for i := 0; i < t.NumField(); i++ {
field := v.Field(i)
tag := t.Field(i).Tag.Get(tagName)
if strings.Contains(tag, ":") {
tag = strings.Split(tag, ":")[1]
}
kind := field.Kind()
var value reflect.Value
if kind == reflect.Ptr {
if !field.IsNil() {
value = field.Elem()
kind = field.Elem().Kind()
} else {
continue
}
} else {
value = field
}
switch kind {
case reflect.String:
out[tag] = value.String()
case reflect.Int:
out[tag] = value.Int()
case reflect.Float64:
out[tag] = value.Float()
case reflect.Bool:
out[tag] = value.Bool()
}
}
return out
}
package search
import (
"math"
"testing"
)
func TestBuild(t *testing.T) {
type TestType struct {
FirstName string `test:"Firstname" json:"testing"` // make sure multiple tags don't break it.
LastName string `test:"Lastname"`
Age int `test:"Age"`
Meh *bool `test:"Meh"`
Meh2 *int `test:"Meh2"`
Pi float64 `test:"Pi"`
}
meh := true
i := TestType{
FirstName: "xealgo",
LastName: "test",
Age: 25,
Meh: &meh,
Pi: math.Pi,
}
// "Meh2" will not even get added to the return value from Build...
o := Build("test", i)
keys := map[string]interface{}{
"Firstname": i.FirstName,
"Lastname": i.LastName,
"Age": int64(i.Age),
"Meh": meh,
"Pi": i.Pi,
}
for ik, iv := range keys {
if ov, ok := o[ik]; ok {
if ov != iv {
t.Errorf("%s value %s expected %s", ik, ov, iv)
}
} else {
t.Errorf("%s not found in output", ik)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment