response.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. ContentLength int64
  19. }
  20. // HasServerFailure returns true if the status code represents a failure.
  21. func (r *Response) HasServerFailure() bool {
  22. return r.StatusCode >= 400
  23. }
  24. // IsModified returns true if the resource has been modified.
  25. func (r *Response) IsModified(etag, lastModified string) bool {
  26. if r.StatusCode == 304 {
  27. return false
  28. }
  29. if r.ETag != "" && r.ETag == etag {
  30. return false
  31. }
  32. if r.LastModified != "" && r.LastModified == lastModified {
  33. return false
  34. }
  35. return true
  36. }
  37. // NormalizeBodyEncoding make sure the body is encoded in UTF-8.
  38. func (r *Response) NormalizeBodyEncoding() (io.Reader, error) {
  39. if strings.Contains(r.ContentType, "charset=") {
  40. return charset.NewReader(r.Body, r.ContentType)
  41. }
  42. return r.Body, nil
  43. }