gclient_response.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
  2. //
  3. // This Source Code Form is subject to the terms of the MIT License.
  4. // If a copy of the MIT was not distributed with this file,
  5. // You can obtain one at https://github.com/gogf/gf.
  6. package gclient
  7. import (
  8. "bytes"
  9. "io/ioutil"
  10. "net/http"
  11. "github.com/gogf/gf/v2/internal/intlog"
  12. )
  13. // Response is the struct for client request response.
  14. type Response struct {
  15. *http.Response // Response is the underlying http.Response object of certain request.
  16. request *http.Request // Request is the underlying http.Request object of certain request.
  17. requestBody []byte // The body bytes of certain request, only available in Dump feature.
  18. cookies map[string]string // Response cookies, which are only parsed once.
  19. }
  20. // initCookie initializes the cookie map attribute of Response.
  21. func (r *Response) initCookie() {
  22. if r.cookies == nil {
  23. r.cookies = make(map[string]string)
  24. // Response might be nil.
  25. if r.Response != nil {
  26. for _, v := range r.Cookies() {
  27. r.cookies[v.Name] = v.Value
  28. }
  29. }
  30. }
  31. }
  32. // GetCookie retrieves and returns the cookie value of specified `key`.
  33. func (r *Response) GetCookie(key string) string {
  34. r.initCookie()
  35. return r.cookies[key]
  36. }
  37. // GetCookieMap retrieves and returns a copy of current cookie values map.
  38. func (r *Response) GetCookieMap() map[string]string {
  39. r.initCookie()
  40. m := make(map[string]string, len(r.cookies))
  41. for k, v := range r.cookies {
  42. m[k] = v
  43. }
  44. return m
  45. }
  46. // ReadAll retrieves and returns the response content as []byte.
  47. func (r *Response) ReadAll() []byte {
  48. // Response might be nil.
  49. if r == nil || r.Response == nil {
  50. return []byte{}
  51. }
  52. body, err := ioutil.ReadAll(r.Response.Body)
  53. if err != nil {
  54. intlog.Errorf(r.request.Context(), `%+v`, err)
  55. return nil
  56. }
  57. return body
  58. }
  59. // ReadAllString retrieves and returns the response content as string.
  60. func (r *Response) ReadAllString() string {
  61. return string(r.ReadAll())
  62. }
  63. // SetBodyContent overwrites response content with custom one.
  64. func (r *Response) SetBodyContent(content []byte) {
  65. buffer := bytes.NewBuffer(content)
  66. r.Body = ioutil.NopCloser(buffer)
  67. r.ContentLength = int64(buffer.Len())
  68. }
  69. // Close closes the response when it will never be used.
  70. func (r *Response) Close() error {
  71. if r == nil || r.Response == nil {
  72. return nil
  73. }
  74. return r.Response.Body.Close()
  75. }