ghttp_client_response.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. // Copyright 2017 gf Author(https://github.com/gogf/gf). 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 ghttp
  7. import (
  8. "io/ioutil"
  9. "net/http"
  10. "github.com/gogf/gf/util/gconv"
  11. )
  12. // ClientResponse is the struct for client request response.
  13. type ClientResponse struct {
  14. *http.Response
  15. request *http.Request
  16. requestBody []byte
  17. cookies map[string]string
  18. }
  19. // initCookie initializes the cookie map attribute of ClientResponse.
  20. func (r *ClientResponse) initCookie() {
  21. if r.cookies == nil {
  22. r.cookies = make(map[string]string)
  23. for _, v := range r.Cookies() {
  24. r.cookies[v.Name] = v.Value
  25. }
  26. }
  27. }
  28. // GetCookie retrieves and returns the cookie value of specified <key>.
  29. func (r *ClientResponse) GetCookie(key string) string {
  30. r.initCookie()
  31. return r.cookies[key]
  32. }
  33. // GetCookieMap retrieves and returns a copy of current cookie values map.
  34. func (r *ClientResponse) GetCookieMap() map[string]string {
  35. r.initCookie()
  36. m := make(map[string]string, len(r.cookies))
  37. for k, v := range r.cookies {
  38. m[k] = v
  39. }
  40. return m
  41. }
  42. // ReadAll retrieves and returns the response content as []byte.
  43. func (r *ClientResponse) ReadAll() []byte {
  44. body, err := ioutil.ReadAll(r.Response.Body)
  45. if err != nil {
  46. return nil
  47. }
  48. return body
  49. }
  50. // ReadAllString retrieves and returns the response content as string.
  51. func (r *ClientResponse) ReadAllString() string {
  52. return gconv.UnsafeBytesToStr(r.ReadAll())
  53. }
  54. // Close closes the response when it will never be used.
  55. func (r *ClientResponse) Close() error {
  56. if r == nil || r.Response == nil || r.Response.Close {
  57. return nil
  58. }
  59. r.Response.Close = true
  60. return r.Response.Body.Close()
  61. }