response.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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 client
  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. // IsNotFound returns true if the resource doesn't exists anymore.
  23. func (r *Response) IsNotFound() bool {
  24. return r.StatusCode == 404 || r.StatusCode == 410
  25. }
  26. // IsNotAuthorized returns true if the resource require authentication.
  27. func (r *Response) IsNotAuthorized() bool {
  28. return r.StatusCode == 401
  29. }
  30. // HasServerFailure returns true if the status code represents a failure.
  31. func (r *Response) HasServerFailure() bool {
  32. return r.StatusCode >= 400
  33. }
  34. // IsModified returns true if the resource has been modified.
  35. func (r *Response) IsModified(etag, lastModified string) bool {
  36. if r.StatusCode == 304 {
  37. return false
  38. }
  39. if r.ETag != "" && r.ETag == etag {
  40. return false
  41. }
  42. if r.LastModified != "" && r.LastModified == lastModified {
  43. return false
  44. }
  45. return true
  46. }
  47. // NormalizeBodyEncoding make sure the body is encoded in UTF-8.
  48. //
  49. // If a charset other than UTF-8 is detected, we convert the document to UTF-8.
  50. // This is used by the scraper and feed readers.
  51. //
  52. // Do not forget edge cases:
  53. // - Some non-utf8 feeds specify encoding only in Content-Type, not in XML document.
  54. func (r *Response) NormalizeBodyEncoding() (io.Reader, error) {
  55. _, params, err := mime.ParseMediaType(r.ContentType)
  56. if err == nil {
  57. if enc, found := params["charset"]; found {
  58. enc = strings.ToLower(enc)
  59. if enc != "utf-8" && enc != "utf8" && enc != "" {
  60. logger.Debug("[NormalizeBodyEncoding] Convert body to UTF-8 from %s", enc)
  61. return charset.NewReader(r.Body, r.ContentType)
  62. }
  63. }
  64. }
  65. return r.Body, nil
  66. }