response.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. // Copyright 2017 Frédéric Guillot. All rights reserved.
  2. // Use of this source code is governed by the Apache 2.0
  3. // license that can be found in the LICENSE file.
  4. package http
  5. import (
  6. "io"
  7. "strings"
  8. "golang.org/x/net/html/charset"
  9. )
  10. // Response wraps a server response.
  11. type Response struct {
  12. Body io.Reader
  13. StatusCode int
  14. EffectiveURL string
  15. LastModified string
  16. ETag string
  17. ContentType string
  18. }
  19. // HasServerFailure returns true if the status code represents a failure.
  20. func (r *Response) HasServerFailure() bool {
  21. return r.StatusCode >= 400
  22. }
  23. // IsModified returns true if the resource has been modified.
  24. func (r *Response) IsModified(etag, lastModified string) bool {
  25. if r.StatusCode == 304 {
  26. return false
  27. }
  28. if r.ETag != "" && r.ETag == etag {
  29. return false
  30. }
  31. if r.LastModified != "" && r.LastModified == lastModified {
  32. return false
  33. }
  34. return true
  35. }
  36. // NormalizeBodyEncoding make sure the body is encoded in UTF-8.
  37. func (r *Response) NormalizeBodyEncoding() (io.Reader, error) {
  38. if strings.Contains(r.ContentType, "charset=") {
  39. return charset.NewReader(r.Body, r.ContentType)
  40. }
  41. return r.Body, nil
  42. }