ghttp_client_dump.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. // Copyright 2020 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. "fmt"
  9. "github.com/gogf/gf/internal/utils"
  10. "io/ioutil"
  11. "net/http"
  12. "net/http/httputil"
  13. "github.com/gogf/gf/util/gconv"
  14. )
  15. // dumpTextFormat is the format of the dumped raw string
  16. const dumpTextFormat = `+---------------------------------------------+
  17. | %s |
  18. +---------------------------------------------+
  19. %s
  20. %s
  21. `
  22. // getResponseBody returns the text of the response body.
  23. func getResponseBody(res *http.Response) string {
  24. if res.Body == nil {
  25. return ""
  26. }
  27. bodyContent, _ := ioutil.ReadAll(res.Body)
  28. res.Body = utils.NewReadCloser(bodyContent, true)
  29. return gconv.UnsafeBytesToStr(bodyContent)
  30. }
  31. // RawRequest returns the raw content of the request.
  32. func (r *ClientResponse) RawRequest() string {
  33. // ClientResponse can be nil.
  34. if r == nil {
  35. return ""
  36. }
  37. if r.request == nil {
  38. return ""
  39. }
  40. // DumpRequestOut writes more request headers than DumpRequest, such as User-Agent.
  41. bs, err := httputil.DumpRequestOut(r.request, false)
  42. if err != nil {
  43. return ""
  44. }
  45. return fmt.Sprintf(
  46. dumpTextFormat,
  47. "REQUEST ",
  48. gconv.UnsafeBytesToStr(bs),
  49. r.requestBody,
  50. )
  51. }
  52. // RawResponse returns the raw content of the response.
  53. func (r *ClientResponse) RawResponse() string {
  54. // ClientResponse can be nil.
  55. if r == nil || r.Response == nil {
  56. return ""
  57. }
  58. bs, err := httputil.DumpResponse(r.Response, false)
  59. if err != nil {
  60. return ""
  61. }
  62. return fmt.Sprintf(
  63. dumpTextFormat,
  64. "RESPONSE",
  65. gconv.UnsafeBytesToStr(bs),
  66. getResponseBody(r.Response),
  67. )
  68. }
  69. // Raw returns the raw text of the request and the response.
  70. func (r *ClientResponse) Raw() string {
  71. return fmt.Sprintf("%s\n%s", r.RawRequest(), r.RawResponse())
  72. }
  73. // RawDump outputs the raw text of the request and the response to stdout.
  74. func (r *ClientResponse) RawDump() {
  75. fmt.Println(r.Raw())
  76. }