responses.go 976 B

12345678910111213141516171819202122232425262728293031323334353637
  1. package httpc
  2. import (
  3. "net/http"
  4. "strings"
  5. "github.com/zeromicro/go-zero/core/mapping"
  6. "github.com/zeromicro/go-zero/rest/internal/encoding"
  7. "github.com/zeromicro/go-zero/rest/internal/header"
  8. )
  9. // Parse parses the response.
  10. func Parse(resp *http.Response, val interface{}) error {
  11. if err := ParseHeaders(resp, val); err != nil {
  12. return err
  13. }
  14. return ParseJsonBody(resp, val)
  15. }
  16. // ParseHeaders parses the rsponse headers.
  17. func ParseHeaders(resp *http.Response, val interface{}) error {
  18. return encoding.ParseHeaders(resp.Header, val)
  19. }
  20. // ParseJsonBody parses the rsponse body, which should be in json content type.
  21. func ParseJsonBody(resp *http.Response, val interface{}) error {
  22. if withJsonBody(resp) {
  23. return mapping.UnmarshalJsonReader(resp.Body, val)
  24. }
  25. return mapping.UnmarshalJsonMap(nil, val)
  26. }
  27. func withJsonBody(r *http.Response) bool {
  28. return r.ContentLength > 0 && strings.Contains(r.Header.Get(header.ContentType), header.ApplicationJson)
  29. }