-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenerate.go
78 lines (70 loc) · 1.55 KB
/
generate.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
package runtimestruct
import (
"encoding/json"
"io"
"io/ioutil"
"reflect"
"unicode"
"unsafe"
)
func NewFromJSON(r io.Reader) (interface{}, error) {
data, err := ioutil.ReadAll(r)
if err != nil {
return nil, err
}
var m map[string]interface{}
err = json.Unmarshal(data, &m)
if err != nil {
return nil, err
}
return generateStruct(m), nil
}
func generateStruct(m map[string]interface{}) interface{} {
fields := make([]reflect.StructField, 0, len(m))
values := make([]interface{}, 0, len(m))
for name, value := range m {
if object, isObject := value.(map[string]interface{}); isObject {
value = generateStruct(object)
}
typ := reflect.TypeOf(value)
if typ == nil {
typ = reflect.TypeOf((*struct{})(nil)) // typed nil
}
path := ""
if !isExported(name) {
path = "github.com/GreenHedgehog/runtimestruct"
}
fields = append(fields, reflect.StructField{
Name: name,
PkgPath: path,
Type: typ,
})
values = append(values, value)
}
object := reflect.New(reflect.StructOf(fields))
for i := 0; i < len(m); i++ {
field := object.Elem().Field(i)
makeSettable(&field)
if values[i] != nil {
field.Set(reflect.ValueOf(values[i]))
}
}
return object.Elem().Interface()
}
func makeSettable(field *reflect.Value) {
if field.CanSet() {
return
}
addr := field.UnsafeAddr()
*field = reflect.NewAt(
field.Type(),
unsafe.Pointer(addr),
).Elem()
}
func isExported(fieldName string) bool {
for _, r := range fieldName {
return unicode.IsUpper(r) && unicode.IsLetter(r)
}
// would never happen
return false
}