encoding.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. // Copyright 2018 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 encoding // import "miniflux.app/reader/encoding"
  5. import (
  6. "bytes"
  7. "io"
  8. "unicode/utf8"
  9. "golang.org/x/net/html/charset"
  10. )
  11. // CharsetReader is used when the XML encoding is specified for the input document.
  12. //
  13. // The document is converted in UTF-8 only if a different encoding is specified
  14. // and the document is not already UTF-8.
  15. //
  16. // Several edge cases could exists:
  17. //
  18. // - Feeds with encoding specified only in Content-Type header and not in XML document
  19. // - Feeds with encoding specified in both places
  20. // - Feeds with encoding specified only in XML document and not in HTTP header
  21. // - Feeds with wrong encoding defined and already in UTF-8
  22. func CharsetReader(label string, input io.Reader) (io.Reader, error) {
  23. buffer, _ := io.ReadAll(input)
  24. r := bytes.NewReader(buffer)
  25. // The document is already UTF-8, do not do anything (avoid double-encoding).
  26. // That means the specified encoding in XML prolog is wrong.
  27. if utf8.Valid(buffer) {
  28. return r, nil
  29. }
  30. // Transform document to UTF-8 from the specified encoding in XML prolog.
  31. return charset.NewReaderLabel(label, r)
  32. }