gclient_dump.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. "fmt"
  9. "io/ioutil"
  10. "net/http"
  11. "net/http/httputil"
  12. "github.com/gogf/gf/v2/internal/intlog"
  13. "github.com/gogf/gf/v2/internal/utils"
  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 string(bodyContent)
  30. }
  31. // RawRequest returns the raw content of the request.
  32. func (r *Response) RawRequest() string {
  33. // Response can be nil.
  34. if r == nil || r.request == nil {
  35. return ""
  36. }
  37. // DumpRequestOut writes more request headers than DumpRequest, such as User-Agent.
  38. bs, err := httputil.DumpRequestOut(r.request, false)
  39. if err != nil {
  40. intlog.Errorf(r.request.Context(), `%+v`, err)
  41. return ""
  42. }
  43. return fmt.Sprintf(
  44. dumpTextFormat,
  45. "REQUEST ",
  46. string(bs),
  47. r.requestBody,
  48. )
  49. }
  50. // RawResponse returns the raw content of the response.
  51. func (r *Response) RawResponse() string {
  52. // Response might be nil.
  53. if r == nil || r.Response == nil {
  54. return ""
  55. }
  56. bs, err := httputil.DumpResponse(r.Response, false)
  57. if err != nil {
  58. intlog.Errorf(r.request.Context(), `%+v`, err)
  59. return ""
  60. }
  61. return fmt.Sprintf(
  62. dumpTextFormat,
  63. "RESPONSE",
  64. string(bs),
  65. getResponseBody(r.Response),
  66. )
  67. }
  68. // Raw returns the raw text of the request and the response.
  69. func (r *Response) Raw() string {
  70. return fmt.Sprintf("%s\n%s", r.RawRequest(), r.RawResponse())
  71. }
  72. // RawDump outputs the raw text of the request and the response to stdout.
  73. func (r *Response) RawDump() {
  74. fmt.Println(r.Raw())
  75. }