/
infer.go
148 lines (118 loc) · 2.61 KB
/
infer.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
package inference
import (
"strconv"
"errors"
"github.com/michael-golfi/log4go"
"reflect"
"encoding/json"
"strings"
"io"
"github.com/davecgh/go-spew/spew"
)
type Field struct {
Name string `json: "Name"`
Type string `json: "Type"`
SubObject []Field `json: "SubOject,omitempty"`
}
type Parser struct {
}
// Force use of json number type
func (j *Parser) ParseString(js string) ([]Field, error) {
var data interface{}
d := json.NewDecoder(strings.NewReader(js))
d.UseNumber()
err := d.Decode(&data)
if err != nil {
return nil, err
}
fields, _ := parse(data)
return fields, nil
}
func (p *Parser) ParseReader(r io.Reader) ([]Field, error) {
var data interface{}
d := json.NewDecoder(r)
d.UseNumber()
err := d.Decode(&data)
if err != nil {
return nil, err
}
fields, _ := parse(data)
return fields, nil
}
func (j *Parser) Parse(msg interface{}) ([]Field, error) {
data, _ := parse(msg)
spew.Dump(data)
return data, nil
}
// Checks if the actual fields tree is a superset of the expected fields
func (p *Parser) FuzzyEqual(expected, actual []Field) bool {
for _, exp := range expected {
var actualVal Field
var err error
actualVal, err = whereKeyEquals(actual, exp.Name)
if err != nil {
log4go.Error("FuzzyEqual: Cannot find key: %s", exp.Name)
return false
}
if actualVal.Type == "array" || actualVal.Type == "object" {
if !p.FuzzyEqual(exp.SubObject, actualVal.SubObject) {
log4go.Error("FuzzyEqual: !eq")
return false
}
} else {
if exp.Type == "float" && actualVal.Type == "int" {
continue;
}
if !reflect.DeepEqual(exp, actualVal) {
log4go.Error("DeepEqual: Not equal")
return false
}
}
}
return true
}
func whereKeyEquals(fields []Field, name string) (Field, error) {
for i := range fields {
if fields[i].Name == name {
return fields[i], nil
}
}
return Field{}, errors.New("Obj Not Found")
}
func parse(in interface{}) ([]Field, string) {
var data []Field
switch t := in.(type){
case []interface{}:
for i, v := range t {
sub, typeStr := parse(v)
field := Field{
Name: strconv.Itoa(i),
Type: typeStr,
SubObject: sub,
}
data = append(data, field)
}
return data, "array"
case map[string]interface{}:
for k, v := range t {
sub, typeStr := parse(v)
field := Field{
Name: k,
Type: typeStr,
SubObject: sub,
}
data = append(data, field)
}
return data, "object"
case string:
return nil, "string"
case json.Number:
if _, err := t.Int64(); err == nil {
return nil, "int"
}
if _, err := t.Float64(); err == nil {
return nil, "float"
}
}
return nil, ""
}