responses.go 909 B

123456789101112131415161718192021222324252627282930313233343536
  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. )
  8. // Parse parses the response.
  9. func Parse(resp *http.Response, val interface{}) error {
  10. if err := ParseHeaders(resp, val); err != nil {
  11. return err
  12. }
  13. return ParseJsonBody(resp, val)
  14. }
  15. // ParseHeaders parses the rsponse headers.
  16. func ParseHeaders(resp *http.Response, val interface{}) error {
  17. return encoding.ParseHeaders(resp.Header, val)
  18. }
  19. // ParseJsonBody parses the rsponse body, which should be in json content type.
  20. func ParseJsonBody(resp *http.Response, val interface{}) error {
  21. if withJsonBody(resp) {
  22. return mapping.UnmarshalJsonReader(resp.Body, val)
  23. }
  24. return mapping.UnmarshalJsonMap(nil, val)
  25. }
  26. func withJsonBody(r *http.Response) bool {
  27. return r.ContentLength > 0 && strings.Contains(r.Header.Get(contentType), applicationJson)
  28. }