-
-
Notifications
You must be signed in to change notification settings - Fork 12
/
json.go
83 lines (71 loc) · 1.88 KB
/
json.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
package httptest
import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"github.com/gobuffalo/httptest/internal/takeon/github.com/markbates/hmax"
)
type JSON struct {
URL string
handler *Handler
Headers map[string]string
Username string
Password string
}
type JSONResponse struct {
*Response
}
func (r *JSONResponse) Bind(x interface{}) {
json.NewDecoder(r.Body).Decode(&x)
}
func (r *JSON) Get() *JSONResponse {
req, _ := http.NewRequest("GET", r.URL, nil)
return r.Perform(req)
}
func (r *JSON) Delete() *JSONResponse {
req, _ := http.NewRequest("DELETE", r.URL, nil)
return r.Perform(req)
}
func (r *JSON) Post(body interface{}) *JSONResponse {
b, _ := json.Marshal(body)
req, _ := http.NewRequest("POST", r.URL, bytes.NewReader(b))
return r.Perform(req)
}
func (r *JSON) Put(body interface{}) *JSONResponse {
b, _ := json.Marshal(body)
req, _ := http.NewRequest("PUT", r.URL, bytes.NewReader(b))
return r.Perform(req)
}
func (r *JSON) Patch(body interface{}) *JSONResponse {
b, _ := json.Marshal(body)
req, _ := http.NewRequest("PATCH", r.URL, bytes.NewReader(b))
return r.Perform(req)
}
func (r *JSON) Do(method string, body interface{}) (*JSONResponse, error) {
b, err := json.Marshal(body)
if err != nil {
return nil, err
}
req, err := http.NewRequest(method, r.URL, bytes.NewReader(b))
if err != nil {
return nil, err
}
return r.Perform(req), nil
}
func (r *JSON) Perform(req *http.Request) *JSONResponse {
if r.handler.HmaxSecret != "" {
hmax.SignRequest(req, []byte(r.handler.HmaxSecret))
}
if r.Username != "" || r.Password != "" {
req.SetBasicAuth(r.Username, r.Password)
}
res := &JSONResponse{&Response{httptest.NewRecorder()}}
for key, value := range r.Headers {
req.Header.Set(key, value)
}
req.Header.Set("Cookie", r.handler.Cookies)
r.handler.ServeHTTP(res, req)
r.handler.Cookies = res.Header().Get("Set-Cookie")
return res
}