-
Notifications
You must be signed in to change notification settings - Fork 0
/
unmarshal.go
391 lines (340 loc) · 7.51 KB
/
unmarshal.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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
package goxtag
import (
"bytes"
"golang.org/x/net/html"
"reflect"
"regexp"
"strconv"
"strings"
)
type Unmarshaler interface {
UnmarshalHTML([]*html.Node) error
}
type valFunc func(doc *Document) string
type xpathTag struct {
tag string
required bool
}
const (
tagName = "xpath"
ignoreTag = "-"
requiredTag = "xpath_required"
)
var (
textVal valFunc = func(doc *Document) string {
return strings.TrimSpace(doc.Text())
}
indexRegEx = regexp.MustCompile(`\[\d+\]$`)
)
func (tag *xpathTag) valFunc() valFunc {
return textVal
}
func (tag *xpathTag) hasIndex() bool {
return indexRegEx.MatchString(tag.tag)
}
func (tag *xpathTag) hasSuffix(s string) bool {
return strings.HasSuffix(tag.tag, s)
}
// Unmarshal takes a byte slice and a destination pointer to any
// interface{}, and unmarshals the document into the destination based on the
// rules above. Any error returned here will likely be of type
// CannotUnmarshalError, though an initial htmlquery error will pass through
// directly.
func Unmarshal(bs []byte, v interface{}) error {
root, err := html.Parse(bytes.NewReader(bs))
if err != nil {
return err
}
return UnmarshalSelection(NewDocumentWithNode(root), v)
}
func wrapUnmErr(err error, v reflect.Value) error {
if err == nil {
return nil
}
return &CannotUnmarshalError{
V: v,
Reason: customUnmarshalError,
Err: err,
}
}
func UnmarshalSelection(doc *Document, iface interface{}) error {
v := reflect.ValueOf(iface)
// Must come before v.IsNil() else IsNil panics on NonPointer value
if v.Kind() != reflect.Ptr {
return &CannotUnmarshalError{
V: v,
Reason: nonPointer,
}
}
if iface == nil || v.IsNil() {
return &CannotUnmarshalError{
V: v,
Reason: nilDestination,
}
}
u, v := indirect(v)
if u != nil {
return wrapUnmErr(u.UnmarshalHTML(doc.Nodes), v)
}
return unmarshalByType(doc, v, xpathTag{})
}
func findByTag(doc *Document, tag xpathTag) (*Document, error) {
if tag.tag != "" {
return doc.Find(tag.tag), nil
}
return doc, nil
}
func findOneByTag(doc *Document, tag xpathTag) (*Document, error) {
if tag.tag != "" {
return doc.FindOne(tag.tag)
}
return doc, nil
}
func findForTypeByTag(doc *Document, v reflect.Value, tag xpathTag) (*Document, error) {
var sel *Document
var err error
hasIndex := tag.hasIndex()
hasTextSuffix := tag.hasSuffix("text()")
switch {
case hasIndex && !hasTextSuffix:
sel, err = findOneByTag(doc, tag)
default:
sel, err = findByTag(doc, tag)
}
if err != nil {
return nil, err
}
t := v.Type()
//type may have custom Unmarshal, check unsupported types later
switch t.Kind() {
case reflect.Struct:
return sel, nil
case reflect.Slice:
return sel, nil
case reflect.Array:
return sel, nil
case reflect.Map:
return sel, nil
case reflect.Interface:
return sel, nil
case reflect.Ptr:
return sel, nil
default:
if hasIndex || hasTextSuffix {
return sel, nil
}
_sel, err := findByTag(doc, tag)
if err != nil {
return nil, err
}
if _sel.Length() > 1 {
return nil, &CannotUnmarshalError{
V: v,
Reason: multipleNodesDetected,
XPath: tag.tag,
}
}
return sel, nil
}
}
func unmarshalByType(doc *Document, v reflect.Value, tag xpathTag) error {
u, v := indirect(v)
if u != nil {
return wrapUnmErr(u.UnmarshalHTML(doc.Nodes), v)
}
// Handle special cases where we can just set the value directly
switch val := v.Interface().(type) {
case []*html.Node:
val = append(val, doc.Nodes...)
v.Set(reflect.ValueOf(val))
return nil
}
t := v.Type()
switch t.Kind() {
case reflect.Struct:
return unmarshalStruct(doc, v)
case reflect.Slice:
return unmarshalSlice(doc, v, tag)
case reflect.Array:
return unmarshalArray(doc, v, tag)
case reflect.Map:
return &CannotUnmarshalError{
V: v,
Reason: mapIsNotSupportedError,
XPath: tag.tag,
}
default:
vf := tag.valFunc()
str := vf(doc)
err := unmarshalLiteral(str, v, tag.required)
if err != nil {
return &CannotUnmarshalError{
V: v,
Reason: typeConversionError,
XPath: tag.tag,
Err: err,
Val: str,
}
}
return nil
}
}
func unmarshalLiteral(s string, v reflect.Value, required bool) error {
t := v.Type()
trimmedValue := strings.TrimSpace(s)
switch t.Kind() {
case reflect.Interface:
if t.NumMethod() == 0 {
// For empty interfaces, just set to a string
nv := reflect.New(reflect.TypeOf(s)).Elem()
nv.Set(reflect.ValueOf(s))
v.Set(nv)
}
case reflect.Bool:
i, err := strconv.ParseBool(trimmedValue)
if err != nil {
return err
}
v.SetBool(i)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
if trimmedValue == "" {
return nil
}
i, err := strconv.ParseInt(trimmedValue, 10, 64)
if err != nil {
if required {
return err
}
return nil
}
v.SetInt(i)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
if trimmedValue == "" {
return nil
}
i, err := strconv.ParseUint(trimmedValue, 10, 64)
if err != nil {
if required {
return err
}
return nil
}
v.SetUint(i)
case reflect.Float32, reflect.Float64:
if trimmedValue == "" {
return nil
}
i, err := strconv.ParseFloat(trimmedValue, 64)
if err != nil {
if required {
return err
}
return nil
}
v.SetFloat(i)
case reflect.String:
v.SetString(s)
}
return nil
}
func unmarshalStruct(doc *Document, v reflect.Value) error {
t := v.Type()
for i := 0; i < t.NumField(); i++ {
tag := xpathTag{
tag: t.Field(i).Tag.Get(tagName),
required: true,
}
if tag.tag == ignoreTag {
continue
}
if tag.tag == "" {
if u, _ := indirect(v.Field(i)); u == nil {
continue
}
}
// If tag is empty and the object doesn't implement Unmarshaler, skip
if tag.tag == "" {
if u, _ := indirect(v.Field(i)); u == nil {
continue
}
}
required := t.Field(i).Tag.Get(requiredTag)
if required != "" {
var err error
tag.required, err = strconv.ParseBool(required)
if err != nil {
return err
}
}
sel, err := findForTypeByTag(doc, v.Field(i), tag)
if err != nil {
return err
}
if !tag.required && sel.IsEmpty() {
continue
}
if sel.IsEmpty() {
return &CannotUnmarshalError{
V: v,
Reason: nodeNotFound,
XPath: tag.tag,
}
}
if err := unmarshalByType(sel, v.Field(i), tag); err != nil {
return &CannotUnmarshalError{
V: v,
Reason: typeConversionError,
XPath: tag.tag,
Err: err,
FldOrIdx: t.Field(i).Name,
}
}
}
return nil
}
func unmarshalArray(doc *Document, v reflect.Value, tag xpathTag) error {
if v.Type().Len() != len(doc.Nodes) {
return &CannotUnmarshalError{
V: v,
Reason: arrayLengthMismatch,
XPath: tag.tag,
}
}
for i := 0; i < v.Type().Len(); i++ {
err := unmarshalByType(doc.Eq(i), v.Index(i), tag)
if err != nil {
return &CannotUnmarshalError{
V: v,
Reason: typeConversionError,
XPath: tag.tag,
Err: err,
FldOrIdx: i,
}
}
}
return nil
}
func unmarshalSlice(doc *Document, v reflect.Value, tag xpathTag) error {
slice := v
eleT := v.Type().Elem()
v.SetLen(0)
for i := 0; i < doc.Length(); i++ {
newV := reflect.New(TypeDeref(eleT))
err := unmarshalByType(doc.Eq(i), newV, tag)
if err != nil {
return &CannotUnmarshalError{
V: v,
Reason: typeConversionError,
XPath: tag.tag,
Err: err,
FldOrIdx: i,
}
}
if eleT.Kind() != reflect.Ptr {
newV = newV.Elem()
}
v = reflect.Append(v, newV)
}
slice.Set(v)
return nil
}