internal/templates/rss.go
72 Zeilen · 1.6 KB · Go
| 1 | package templates |
| 2 | |
| 3 | import ( |
| 4 | "encoding/xml" |
| 5 | "io" |
| 6 | "time" |
| 7 | |
| 8 | "github.com/ruedigerp/newblog/internal/content" |
| 9 | ) |
| 10 | |
| 11 | type rssChannel struct { |
| 12 | XMLName xml.Name `xml:"channel"` |
| 13 | Title string `xml:"title"` |
| 14 | Link string `xml:"link"` |
| 15 | Description string `xml:"description"` |
| 16 | Language string `xml:"language"` |
| 17 | LastBuildDate string `xml:"lastBuildDate"` |
| 18 | Items []rssItem `xml:"item"` |
| 19 | } |
| 20 | |
| 21 | type rssItem struct { |
| 22 | Title string `xml:"title"` |
| 23 | Link string `xml:"link"` |
| 24 | Description string `xml:"description"` |
| 25 | PubDate string `xml:"pubDate"` |
| 26 | GUID string `xml:"guid"` |
| 27 | } |
| 28 | |
| 29 | type rssFeed struct { |
| 30 | XMLName xml.Name `xml:"rss"` |
| 31 | Version string `xml:"version,attr"` |
| 32 | Channel rssChannel `xml:"channel"` |
| 33 | } |
| 34 | |
| 35 | func RenderRSS(w io.Writer, site SiteData, posts []*content.Post) error { |
| 36 | items := make([]rssItem, 0, len(posts)) |
| 37 | for _, p := range posts { |
| 38 | link := site.BaseURL + "/posts/" + p.Slug + "/" |
| 39 | desc := p.GetPreview() |
| 40 | items = append(items, rssItem{ |
| 41 | Title: p.Title, |
| 42 | Link: link, |
| 43 | Description: desc, |
| 44 | PubDate: p.Date.Format(time.RFC1123Z), |
| 45 | GUID: link, |
| 46 | }) |
| 47 | } |
| 48 | |
| 49 | buildDate := time.Now().Format(time.RFC1123Z) |
| 50 | if len(posts) > 0 { |
| 51 | buildDate = posts[0].Date.Format(time.RFC1123Z) |
| 52 | } |
| 53 | |
| 54 | feed := rssFeed{ |
| 55 | Version: "2.0", |
| 56 | Channel: rssChannel{ |
| 57 | Title: site.Title, |
| 58 | Link: site.BaseURL, |
| 59 | Description: site.Description, |
| 60 | Language: "de-de", |
| 61 | LastBuildDate: buildDate, |
| 62 | Items: items, |
| 63 | }, |
| 64 | } |
| 65 | |
| 66 | if _, err := w.Write([]byte(xml.Header)); err != nil { |
| 67 | return err |
| 68 | } |
| 69 | enc := xml.NewEncoder(w) |
| 70 | enc.Indent("", " ") |
| 71 | return enc.Encode(feed) |
| 72 | } |