body.go 890 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. package http
  2. import (
  3. "compress/gzip"
  4. "compress/zlib"
  5. "golang.org/x/net/html/charset"
  6. "io"
  7. "net/http"
  8. )
  9. func DecodeResponse(response *http.Response) ([]byte, error) {
  10. var (
  11. contentEncoding = response.Header.Get("Content-Encoding")
  12. contentType = response.Header.Get("Content-Type")
  13. reader io.Reader = response.Body
  14. )
  15. if "gzip" == contentEncoding {
  16. if r, err := gzip.NewReader(response.Body); err == nil {
  17. //goland:noinspection ALL
  18. defer r.Close()
  19. reader = r
  20. }
  21. } else if "deflate" == contentEncoding {
  22. if r, err := zlib.NewReader(response.Body); err == nil {
  23. //goland:noinspection ALL
  24. defer r.Close()
  25. reader = r
  26. }
  27. }
  28. if "application/octet-stream" != contentType {
  29. if r, err := charset.NewReader(reader, contentType); err == nil {
  30. reader = r
  31. } else {
  32. return nil, err
  33. }
  34. }
  35. return io.ReadAll(reader)
  36. }