1
1

feed.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package main
  2. import (
  3. "encoding/xml"
  4. "net/http"
  5. "time"
  6. )
  7. const feedItems = 20
  8. type rss struct {
  9. XMLName xml.Name `xml:"rss"`
  10. Version string `xml:"version,attr"`
  11. DC string `xml:"xmlns:dc,attr"` // Dublin Core, for dc:creator
  12. Channel rssChannel `xml:"channel"`
  13. }
  14. type rssChannel struct {
  15. Title string `xml:"title"`
  16. Link string `xml:"link"`
  17. Description string `xml:"description"`
  18. LastBuildDate string `xml:"lastBuildDate,omitempty"`
  19. Items []rssItem `xml:"item"`
  20. }
  21. type rssItem struct {
  22. Title string `xml:"title"`
  23. Link string `xml:"link"`
  24. GUID string `xml:"guid"`
  25. PubDate string `xml:"pubDate"`
  26. Description string `xml:"description,omitempty"`
  27. // RSS's own <author> must be an email address; dc:creator takes a name.
  28. Creator string `xml:"dc:creator,omitempty"`
  29. }
  30. func (a *app) feed(w http.ResponseWriter, r *http.Request) {
  31. idx, err := a.store.Index()
  32. if err != nil {
  33. a.serverError(w, err)
  34. return
  35. }
  36. ch := rssChannel{
  37. Title: a.siteName,
  38. Link: a.siteURL + "/",
  39. Description: "Posts from " + a.siteName,
  40. }
  41. for i, p := range idx.posts {
  42. if i == feedItems {
  43. break
  44. }
  45. if i == 0 {
  46. ch.LastBuildDate = p.Date.Format(time.RFC1123Z)
  47. }
  48. link := a.siteURL + "/posts/" + p.Slug
  49. ch.Items = append(ch.Items, rssItem{
  50. Title: p.Title,
  51. Link: link,
  52. GUID: link,
  53. PubDate: p.Date.Format(time.RFC1123Z),
  54. Description: p.Summary,
  55. Creator: p.Author,
  56. })
  57. }
  58. out, err := xml.MarshalIndent(rss{Version: "2.0", DC: "http://purl.org/dc/elements/1.1/", Channel: ch}, "", " ")
  59. if err != nil {
  60. a.serverError(w, err)
  61. return
  62. }
  63. w.Header().Set("Content-Type", "application/rss+xml; charset=utf-8")
  64. w.Write([]byte(xml.Header))
  65. w.Write(out)
  66. }