-
Notifications
You must be signed in to change notification settings - Fork 1
/
http_test_client.go
68 lines (53 loc) · 1.39 KB
/
http_test_client.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
package gin
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/http/httptest"
)
type HttpError struct {
Code int64 `json:"code"`
Message string `json:"message"`
}
func (e HttpError) Error() string {
return e.Message
}
type HttpTestClient struct {
handler http.Handler
}
func (c *HttpTestClient) SendGetRequest(path string, resp interface{}) error {
w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", path, nil)
c.handler.ServeHTTP(w, req)
if w.Body == nil {
return fmt.Errorf("server response is nil")
}
bodyBytes, _ := ioutil.ReadAll(w.Body)
if err := c.tryUnmarshalAsError(bodyBytes); err != nil {
return err
}
//reset the response body to the original unread state
w.Body = bytes.NewBuffer(bodyBytes)
return json.NewDecoder(w.Body).Decode(&resp)
}
func (c *HttpTestClient) SendPostRequest(path string, r interface{}, resp interface{}) error {
body, _ := json.Marshal(r)
w := httptest.NewRecorder()
req, _ := http.NewRequest("POST", path, bytes.NewBuffer(body))
c.handler.ServeHTTP(w, req)
if w.Body == nil {
return fmt.Errorf("server response is nil")
}
return json.NewDecoder(w.Body).Decode(&resp)
}
func (c *HttpTestClient) tryUnmarshalAsError(body []byte) error {
dec := json.NewDecoder(bytes.NewBuffer(body))
dec.DisallowUnknownFields()
resp := HttpError{}
if err := dec.Decode(&resp); err == nil {
return resp
}
return nil
}