-
-
Notifications
You must be signed in to change notification settings - Fork 12
/
request.go
105 lines (91 loc) · 2.42 KB
/
request.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
package httptest
import (
"io"
"mime/multipart"
"net/http"
"net/http/httptest"
"net/url"
"reflect"
"strings"
"github.com/gobuffalo/httptest/internal/takeon/github.com/ajg/form"
"github.com/gobuffalo/httptest/internal/takeon/github.com/markbates/hmax"
)
type Request struct {
URL string
handler *Handler
Headers map[string]string
Username string
Password string
}
func (r *Request) SetBasicAuth(username, password string) {
r.Username = username
r.Password = password
}
func (r *Request) Get() *Response {
req, _ := http.NewRequest("GET", r.URL, nil)
return r.Perform(req)
}
func (r *Request) Delete() *Response {
req, _ := http.NewRequest("DELETE", r.URL, nil)
return r.Perform(req)
}
func (r *Request) Post(body interface{}) *Response {
req, _ := http.NewRequest("POST", r.URL, toReader(body))
r.Headers["Content-Type"] = "application/x-www-form-urlencoded"
return r.Perform(req)
}
func (r *Request) Put(body interface{}) *Response {
req, _ := http.NewRequest("PUT", r.URL, toReader(body))
r.Headers["Content-Type"] = "application/x-www-form-urlencoded"
return r.Perform(req)
}
func (r *Request) Do(method string, body interface{}) (*Response, error) {
req, err := http.NewRequest(method, r.URL, toReader(body))
if err != nil {
return nil, err
}
return r.Perform(req), nil
}
func (r *Request) Perform(req *http.Request) *Response {
if r.handler.HmaxSecret != "" {
hmax.SignRequest(req, []byte(r.handler.HmaxSecret))
}
if r.Username != "" || r.Password != "" {
req.SetBasicAuth(r.Username, r.Password)
}
res := &Response{httptest.NewRecorder()}
for key, value := range r.Headers {
req.Header.Set(key, value)
}
req.RequestURI = r.URL
req.Header.Set("Cookie", r.handler.Cookies)
r.handler.ServeHTTP(res, req)
c := res.Header().Get("Set-Cookie")
r.handler.Cookies = c
return res
}
func toReader(body interface{}) io.Reader {
if _, ok := body.(encodable); !ok {
body, _ = form.EncodeToValues(body)
}
return strings.NewReader(body.(encodable).Encode())
}
func toURLValues(body interface{}) url.Values {
m := map[string]interface{}{}
rv := reflect.Indirect(reflect.ValueOf(body))
rt := rv.Type()
for i := 0; i < rt.NumField(); i++ {
tf := rt.Field(i)
rf := rv.Field(i)
if _, ok := rf.Interface().(multipart.File); ok {
continue
}
if n, ok := tf.Tag.Lookup("form"); ok {
m[n] = rf.Interface()
continue
}
m[tf.Name] = rf.Interface()
}
b, _ := form.EncodeToValues(m)
return b
}