This repository has been archived by the owner on May 14, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
adapter.go
87 lines (70 loc) · 1.97 KB
/
adapter.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
package gotcha
import (
"net/http"
"sync"
)
type Adapter interface {
// DoRequest is a custom function that will be used by gotcha to make the actual request.
DoRequest(options *Options) (*Response, error)
}
// RequestAdapter is a default implementation of Adapter.
// Gotcha will use this adapter when no other is specified.
type RequestAdapter struct {
// RoundTripper is a http.RoundTripper that will be used to do the request.
//
// Defaults to http.DefaultTransport.
RoundTripper http.RoundTripper
// Request is a function that builds the http.Request to send.
//
// Defaults to a function that derives the Request from the specified Options.
Request func(*Options) *http.Request
mu sync.Mutex
}
// Initializes adapter defaults.
func (ra *RequestAdapter) init(options *Options) {
ra.mu.Lock()
if ra.Request == nil {
ra.Request = func(o *Options) *http.Request {
return &http.Request{
Method: o.Method,
URL: o.FullUrl,
Header: o.Headers,
Body: o.Body,
}
}
}
if ra.RoundTripper == nil {
var defaultTransport = http.DefaultTransport.(*http.Transport)
if p := options.Proxy; p != nil {
defaultTransport.Proxy = http.ProxyURL(p)
}
ra.RoundTripper = defaultTransport
}
ra.mu.Unlock()
}
func (ra *RequestAdapter) DoRequest(options *Options) (*Response, error) {
ra.init(options)
req := ra.Request(options)
if options.CookieJar != nil {
for _, cookie := range options.CookieJar.Cookies(options.FullUrl) {
req.AddCookie(cookie)
}
}
res, err := ra.RoundTripper.RoundTrip(req)
if err != nil {
return nil, err
}
if options.CookieJar != nil {
if rc := res.Cookies(); len(rc) > 0 {
options.CookieJar.SetCookies(options.FullUrl, rc)
}
}
return &Response{res, options.UnmarshalJson}, nil
}
// mockAdapter is only used for testing Adapter.
type mockAdapter struct {
OnCalledDoRequest func(*Options) *Response
}
func (ma *mockAdapter) DoRequest(options *Options) (*Response, error) {
return ma.OnCalledDoRequest(options), nil
}