-
Notifications
You must be signed in to change notification settings - Fork 20
/
decoder.go
40 lines (34 loc) · 997 Bytes
/
decoder.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
package goq
import (
"io"
"sync"
"github.com/PuerkitoBio/goquery"
)
// Decoder implements the same API you will see in encoding/xml and
// encoding/json except that we do not currently support proper streaming
// decoding as it is not supported by goquery upstream.
type Decoder struct {
err error
doc *goquery.Document
cache sync.Map
}
// NewDecoder returns a new decoder given an io.Reader
func NewDecoder(r io.Reader) *Decoder {
d := &Decoder{}
d.doc, d.err = goquery.NewDocumentFromReader(r)
return d
}
// Decode will unmarshal the contents of the decoder when given an instance of
// an annotated type as its argument. It will return any errors encountered
// during either parsing the document or unmarshaling into the given object.
func (d *Decoder) Decode(dest interface{}) error {
if d.err != nil {
return d.err
}
if d.doc == nil {
return &CannotUnmarshalError{
Reason: "resulting document was nil",
}
}
return UnmarshalSelection(d.doc.Selection, dest)
}