responses.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package httpc
  2. import (
  3. "bytes"
  4. "io"
  5. "net/http"
  6. "strings"
  7. "github.com/wuntsong-org/go-zero-plus/core/mapping"
  8. "github.com/wuntsong-org/go-zero-plus/rest/internal/encoding"
  9. "github.com/wuntsong-org/go-zero-plus/rest/internal/header"
  10. )
  11. // Parse parses the response.
  12. func Parse(resp *http.Response, val any) error {
  13. if err := ParseHeaders(resp, val); err != nil {
  14. return err
  15. }
  16. return ParseJsonBody(resp, val)
  17. }
  18. // ParseHeaders parses the response headers.
  19. func ParseHeaders(resp *http.Response, val any) error {
  20. return encoding.ParseHeaders(resp.Header, val)
  21. }
  22. // ParseJsonBody parses the response body, which should be in json content type.
  23. func ParseJsonBody(resp *http.Response, val any) error {
  24. defer resp.Body.Close()
  25. if isContentTypeJson(resp) {
  26. if resp.ContentLength > 0 {
  27. return mapping.UnmarshalJsonReader(resp.Body, val)
  28. }
  29. var buf bytes.Buffer
  30. if _, err := io.Copy(&buf, resp.Body); err != nil {
  31. return err
  32. }
  33. if buf.Len() > 0 {
  34. return mapping.UnmarshalJsonReader(&buf, val)
  35. }
  36. }
  37. return mapping.UnmarshalJsonMap(nil, val)
  38. }
  39. func isContentTypeJson(r *http.Response) bool {
  40. return strings.Contains(r.Header.Get(header.ContentType), header.ApplicationJson)
  41. }