-
Notifications
You must be signed in to change notification settings - Fork 5
/
response.go
63 lines (52 loc) · 1.27 KB
/
response.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
package requestgen
import (
"encoding/json"
"io"
"net/http"
)
// Response is wrapper for standard http.Response and provides
// more methods.
type Response struct {
*http.Response
// Body overrides the composited Body field.
Body []byte
}
// NewResponse is a wrapper of the http.Response instance, it reads the response body and close the file.
func NewResponse(r *http.Response) (response *Response, err error) {
body, err := io.ReadAll(r.Body)
if err != nil {
return nil, err
}
err = r.Body.Close()
response = &Response{Response: r, Body: body}
return response, err
}
// String converts response body to string.
// An empty string will be returned if error.
func (r *Response) String() string {
return string(r.Body)
}
func (r *Response) DecodeJSON(o interface{}) error {
// handle 204 - No Content
if r.StatusCode == 204 && len(r.Body) == 0 {
return nil
}
return json.Unmarshal(r.Body, o)
}
func (r *Response) IsError() bool {
return r.StatusCode >= 400
}
func (r *Response) IsJSON() bool {
switch r.Header.Get("content-type") {
case "text/json", "application/json", "application/json; charset=utf-8":
return true
}
return false
}
func (r *Response) IsHTML() bool {
switch r.Header.Get("content-type") {
case "text/html":
return true
}
return false
}