format.go 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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 parser // import "miniflux.app/reader/parser"
  5. import (
  6. "encoding/xml"
  7. "strings"
  8. "miniflux.app/reader/encoding"
  9. )
  10. // List of feed formats.
  11. const (
  12. FormatRDF = "rdf"
  13. FormatRSS = "rss"
  14. FormatAtom = "atom"
  15. FormatJSON = "json"
  16. FormatUnknown = "unknown"
  17. )
  18. // DetectFeedFormat tries to guess the feed format from input data.
  19. func DetectFeedFormat(data string) string {
  20. if strings.HasPrefix(strings.TrimSpace(data), "{") {
  21. return FormatJSON
  22. }
  23. decoder := xml.NewDecoder(strings.NewReader(data))
  24. decoder.CharsetReader = encoding.CharsetReader
  25. for {
  26. token, _ := decoder.Token()
  27. if token == nil {
  28. break
  29. }
  30. if element, ok := token.(xml.StartElement); ok {
  31. switch element.Name.Local {
  32. case "rss":
  33. return FormatRSS
  34. case "feed":
  35. return FormatAtom
  36. case "RDF":
  37. return FormatRDF
  38. }
  39. }
  40. }
  41. return FormatUnknown
  42. }