forked from celrenheit/spider
/
context.go
231 lines (203 loc) · 5.63 KB
/
context.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
package spider
import (
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/http/cookiejar"
"sync"
"time"
"github.com/PuerkitoBio/goquery"
"github.com/bitly/go-simplejson"
"github.com/cenkalti/backoff"
"golang.org/x/net/publicsuffix"
)
var (
ErrNoClient = errors.New("No request has been set")
ErrNoRequest = errors.New("No request has been set")
)
// Context is the element that can be shared accross different spiders.
// It contains an HTTP Client and an HTTP Request.
// Context can execute an HTTP Request.
type Context struct {
Client *http.Client
response *http.Response
request *http.Request
ClientReset bool
Parent *Context
store *store
}
// NewContext returns a new Context.
func NewContext() *Context {
return &Context{
store: NewKVStore(),
}
}
// HTMLParser returns an HTML parser.
//
// It uses PuerkitoBio's awesome goquery package.
// It can be found an this url: https://github.com/PuerkitoBio/goquery.
func (c *Context) HTMLParser() (*goquery.Document, error) {
res := c.Response()
defer res.Body.Close()
return goquery.NewDocumentFromReader(res.Body)
}
// JSONParser returns a JSON parser.
//
// It uses Bitly's go-simplejson package which can be found in: https://github.com/bitly/go-simplejson
func (c *Context) JSONParser() (*simplejson.Json, error) {
res := c.Response()
defer res.Body.Close()
return simplejson.NewFromReader(res.Body)
}
// RAWContent returns the raw data of the reponse's body
func (c *Context) RAWContent() ([]byte, error) {
res := c.Response()
defer res.Body.Close()
return ioutil.ReadAll(res.Body)
}
// Response returns an http.Response
func (c *Context) Response() *http.Response {
return c.response
}
// SetResponse set an http.Response
func (c *Context) SetResponse(res *http.Response) {
c.response = res
}
// SetRequest set an http.Request
func (c *Context) SetRequest(req *http.Request) {
c.request = req
}
// Request returns an http.Response
func (c *Context) Request() *http.Request {
return c.request
}
// Cookies return a list of cookies for the given request URL
func (c *Context) Cookies() []*http.Cookie {
return c.Client.Jar.Cookies(c.Request().URL)
}
// ResetCookies create a new cookie jar.
//
// Note: All the cookies previously will be deleted.
func (c *Context) ResetCookies() error {
jar, err := cookiejar.New(&cookiejar.Options{
PublicSuffixList: publicsuffix.List,
})
if err != nil {
return err
}
c.Client.Jar = jar
return nil
}
// ResetClient create a new http.Client and replace the existing one if there is one.
func (c *Context) ResetClient() (*http.Client, error) {
client, err := c.NewClient()
c.Client = client
return client, err
}
// NewClient create a new http.Client
func (c *Context) NewClient() (*http.Client, error) {
jar, err := c.NewCookieJar()
if err != nil {
return nil, err
}
client := &http.Client{
Jar: jar,
Transport: http.DefaultTransport,
}
c.Client = client
return client, nil
}
// NewCookieJar create a new *cookiejar.Jar
func (c *Context) NewCookieJar() (*cookiejar.Jar, error) {
return cookiejar.New(&cookiejar.Options{
PublicSuffixList: publicsuffix.List,
})
}
// DoRequest makes an http request using the http.Client and http.Request associated with this context.
//
// This will store the response in this context. To access the response you should do:
// ctx.Response() // to get the http.Response
func (c *Context) DoRequest() (*http.Response, error) {
client := c.Client
if client == nil {
client = http.DefaultClient
}
if c.Request() == nil {
return nil, ErrNoRequest
}
res, err := client.Do(c.Request())
if err == nil {
c.SetResponse(res)
}
return res, err
}
// DoRequestWithExponentialBackOff makes an http request using the http.Client and http.Request associated with this context.
// You can pass a condition and a BackOff configuration. See https://github.com/cenkalti/backoff to know more about backoff.
// If no BackOff is provided it will use the default exponential BackOff configuration.
// See also ErrorIfStatusCodeIsNot function that provides a basic condition based on status code.
func (c *Context) DoRequestWithExponentialBackOff(condition BackoffCondition, b backoff.BackOff) (*http.Response, error) {
if b == nil {
b = backoff.NewExponentialBackOff()
}
err := backoff.RetryNotify(
func() error {
var err error
res, err := c.DoRequest()
if err != nil {
return err
}
return condition(res)
},
b,
func(err error, wait time.Duration) {
fmt.Println("˙\nBackoff:Waiting: ", wait)
fmt.Println(err)
fmt.Println("")
})
return c.Response(), err
}
// Set a value to this context
func (c *Context) Set(key string, value interface{}) {
c.store.set(key, value)
}
// Get a value from this context
func (c *Context) Get(key string) interface{} {
return c.store.get(key)
}
// ExtendWithRequest return a new Context child to the provided context associated with the provided http.Request.
func (c *Context) ExtendWithRequest(ctx Context, r *http.Request) *Context {
newCtx := NewContext()
newCtx.SetRequest(r)
newCtx.Parent = c
return newCtx
}
// NewKVStore returns a new store.
func NewKVStore() *store {
return &store{
kv: make(map[string]interface{}),
}
}
type store struct {
sync.RWMutex
kv map[string]interface{}
}
func (s *store) set(key string, value interface{}) {
s.Lock()
defer s.Unlock()
s.kv[key] = value
}
func (s *store) get(key string) interface{} {
s.RLock()
defer s.RUnlock()
return s.kv[key]
}
type BackoffCondition func(*http.Response) error
func ErrorIfStatusCodeIsNot(status int) BackoffCondition {
return func(res *http.Response) error {
if res.StatusCode != status {
return errors.New("Request failed: " + res.Status)
}
return nil
}
}