response.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. "mime"
  8. "strings"
  9. "github.com/miniflux/miniflux/logger"
  10. "golang.org/x/net/html/charset"
  11. )
  12. // Response wraps a server response.
  13. type Response struct {
  14. Body io.Reader
  15. StatusCode int
  16. EffectiveURL string
  17. LastModified string
  18. ETag string
  19. ContentType string
  20. ContentLength int64
  21. }
  22. // HasServerFailure returns true if the status code represents a failure.
  23. func (r *Response) HasServerFailure() bool {
  24. return r.StatusCode >= 400
  25. }
  26. // IsModified returns true if the resource has been modified.
  27. func (r *Response) IsModified(etag, lastModified string) bool {
  28. if r.StatusCode == 304 {
  29. return false
  30. }
  31. if r.ETag != "" && r.ETag == etag {
  32. return false
  33. }
  34. if r.LastModified != "" && r.LastModified == lastModified {
  35. return false
  36. }
  37. return true
  38. }
  39. // NormalizeBodyEncoding make sure the body is encoded in UTF-8.
  40. //
  41. // If a charset other than UTF-8 is detected, we convert the document to UTF-8.
  42. // This is used by the scraper and feed readers.
  43. //
  44. // Do not forget edge cases:
  45. // - Some non-utf8 feeds specify encoding only in Content-Type, not in XML document.
  46. func (r *Response) NormalizeBodyEncoding() (io.Reader, error) {
  47. _, params, err := mime.ParseMediaType(r.ContentType)
  48. if err == nil {
  49. if enc, found := params["charset"]; found {
  50. enc = strings.ToLower(enc)
  51. if enc != "utf-8" && enc != "utf8" && enc != "" {
  52. logger.Debug("[NormalizeBodyEncoding] Convert body to UTF-8 from %s", enc)
  53. return charset.NewReader(r.Body, r.ContentType)
  54. }
  55. }
  56. }
  57. return r.Body, nil
  58. }