This repository has been archived by the owner on Oct 3, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
json.go
71 lines (60 loc) · 1.56 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
package willie
import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"github.com/markbates/hmax"
)
type JSON struct {
URL string
Willie *Willie
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) perform(req *http.Request) *JSONResponse {
if r.Willie.HmaxSecret != "" {
hmax.SignRequest(req, []byte(r.Willie.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.Willie.Cookies)
r.Willie.ServeHTTP(res, req)
r.Willie.Cookies = res.Header().Get("Set-Cookie")
return res
}