common_response.go raw
1 package response
2
3 import (
4 "io"
5 "io/ioutil"
6 "net/http"
7 )
8
9 var hookReadAll = func(fn func(r io.Reader) (b []byte, err error)) func(r io.Reader) (b []byte, err error) {
10 return fn
11 }
12
13 // CommonResponse is for storing message of httpResponse
14 type CommonResponse struct {
15 httpStatus int
16 httpHeaders map[string][]string
17 httpContentString string
18 httpContentBytes []byte
19 }
20
21 // ParseFromHTTPResponse assigns for CommonResponse, returns err when body is too large.
22 func (resp *CommonResponse) ParseFromHTTPResponse(httpResponse *http.Response) (err error) {
23 defer httpResponse.Body.Close()
24 body, err := hookReadAll(ioutil.ReadAll)(httpResponse.Body)
25 if err != nil {
26 return
27 }
28 resp.httpStatus = httpResponse.StatusCode
29 resp.httpHeaders = httpResponse.Header
30 resp.httpContentBytes = body
31 resp.httpContentString = string(body)
32 return
33 }
34
35 // GetHTTPStatus returns httpStatus
36 func (resp *CommonResponse) GetHTTPStatus() int {
37 return resp.httpStatus
38 }
39
40 // GetHTTPHeaders returns httpresponse's headers
41 func (resp *CommonResponse) GetHTTPHeaders() map[string][]string {
42 return resp.httpHeaders
43 }
44
45 // GetHTTPContentString return body content as string
46 func (resp *CommonResponse) GetHTTPContentString() string {
47 return resp.httpContentString
48 }
49
50 // GetHTTPContentBytes return body content as []byte
51 func (resp *CommonResponse) GetHTTPContentBytes() []byte {
52 return resp.httpContentBytes
53 }
54