common_response.go 1.4 KB

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