2
0

http.go 837 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. package tools
  2. import (
  3. "compress/gzip"
  4. "compress/zlib"
  5. "golang.org/x/net/html/charset"
  6. "io"
  7. "net/http"
  8. )
  9. func DecodeHttpResponse(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. defer r.Close()
  18. reader = r
  19. }
  20. } else if "deflate" == contentEncoding {
  21. if r, err := zlib.NewReader(response.Body); err == nil {
  22. defer r.Close()
  23. reader = r
  24. }
  25. }
  26. if "application/octet-stream" != contentType {
  27. if r, err := charset.NewReader(reader, contentType); err == nil {
  28. reader = r
  29. } else {
  30. return nil, err
  31. }
  32. }
  33. return io.ReadAll(reader)
  34. }