format.go 995 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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. rxml "miniflux.app/reader/xml"
  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 := rxml.NewDecoder(strings.NewReader(data))
  24. for {
  25. token, _ := decoder.Token()
  26. if token == nil {
  27. break
  28. }
  29. if element, ok := token.(xml.StartElement); ok {
  30. switch element.Name.Local {
  31. case "rss":
  32. return FormatRSS
  33. case "feed":
  34. return FormatAtom
  35. case "RDF":
  36. return FormatRDF
  37. }
  38. }
  39. }
  40. return FormatUnknown
  41. }