-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathencoder.go
84 lines (66 loc) · 1.82 KB
/
encoder.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package quacktors
import (
"errors"
"fmt"
"github.com/Azer0s/quacktors/typeregister"
"reflect"
)
func encodeValue(messageType string, value interface{}) (ret map[string]interface{}, err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("panic while encoding value %x", r)
}
}()
ret = make(map[string]interface{})
val := reflect.ValueOf(value)
//This should actually never happen
if val.Kind() == reflect.Ptr {
val = val.Elem()
}
valType := val.Type()
for i := 0; i < val.NumField(); i++ {
field := val.Field(i)
switch field.Kind() {
case reflect.Struct:
fallthrough
case reflect.Ptr:
v, err := encodeValue(messageType, field.Interface())
if err != nil {
return nil, err
}
ret[valType.Field(i).Name] = v
default:
ret[valType.Field(i).Name] = field.Interface()
}
}
return ret, nil
}
func decodeValue(messageType string, data map[string]interface{}) (interface{}, error) {
registryVal, ok := typeregister.Load(messageType)
if !ok {
return nil, errors.New("no such type " + messageType)
}
return decodeValueByInterface(registryVal, data)
}
func decodeValueByInterface(template interface{}, data map[string]interface{}) (interface{}, error) {
retType := reflect.ValueOf(template).Type()
ret := reflect.New(retType).Elem()
for s, i := range data {
val := reflect.ValueOf(i)
switch ret.FieldByName(s).Kind() {
case reflect.Struct:
b, ok := i.(map[string]interface{})
if !ok {
return nil, errors.New(s + " is " + reflect.TypeOf(i).String() + " not map[string]interface{}")
}
v, err := decodeValueByInterface(reflect.New(ret.FieldByName(s).Type()).Elem().Interface(), b)
if err != nil {
return nil, err
}
ret.FieldByName(s).Set(reflect.ValueOf(v))
default:
ret.FieldByName(s).Set(val)
}
}
return ret.Interface(), nil
}