all repos — vite @ 4bfc4c0dd5999ee93d7a6bce3de49b56defef117

a fast (this time, actually) and minimal static site generator

atom/feed.go (view raw)

  1package atom
  2
  3import (
  4	"encoding/xml"
  5	"fmt"
  6	"path/filepath"
  7	"time"
  8
  9	"git.icyphox.sh/vite/config"
 10	"git.icyphox.sh/vite/markdown"
 11)
 12
 13type AtomLink struct {
 14	XMLName xml.Name `xml:"link"`
 15	Href    string   `xml:"href,attr"`
 16	Rel     string   `xml:"rel,attr,omitempty"`
 17}
 18
 19type AtomSummary struct {
 20	XMLName xml.Name `xml:"summary"`
 21	Content string   `xml:",chardata"`
 22	Type    string   `xml:"type,attr"`
 23}
 24
 25type AtomAuthor struct {
 26	XMLName xml.Name `xml:"author"`
 27	Name    string   `xml:"name"`
 28	Email   string   `xml:"email"`
 29}
 30
 31type AtomEntry struct {
 32	XMLName xml.Name `xml:"entry"`
 33	Title   string   `xml:"title"`
 34	Updated string   `xml:"updated"`
 35	ID      string   `xml:"id"`
 36	Link    *AtomLink
 37	Summary *AtomSummary
 38}
 39
 40type AtomFeed struct {
 41	XMLName  xml.Name `xml:"feed"`
 42	Xmlns    string   `xml:"xmlns,attr"`
 43	Title    string   `xml:"title"`
 44	Subtitle string   `xml:"subtitle"`
 45	ID       string   `xml:"id"`
 46	Updated  string   `xml:"updated"`
 47	Link     *AtomLink
 48	Author   *AtomAuthor `xml:"author"`
 49	Entries  []AtomEntry
 50}
 51
 52// Creates a new Atom feed.
 53func NewAtomFeed(srcDir string, posts []markdown.Output) ([]byte, error) {
 54	entries := []AtomEntry{}
 55
 56	for _, p := range posts {
 57		dateStr := p.Meta["date"]
 58		date, err := time.Parse("2006-01-02", dateStr)
 59		if err != nil {
 60			return nil, err
 61		}
 62		rfc3339 := date.Format(time.RFC3339)
 63
 64		entry := AtomEntry{
 65			Title:   p.Meta["title"],
 66			Updated: rfc3339,
 67			// tag:icyphox.sh,2019-10-23:blog/some-post/
 68			ID: fmt.Sprintf(
 69				"tag:%s,%s:%s",
 70				config.Config.URL[8:], // strip https://
 71				dateStr,
 72				filepath.Join(srcDir, p.Meta["slug"]),
 73			),
 74			// filepath.Join strips the second / in http://
 75			Link: &AtomLink{Href: config.Config.URL + filepath.Join(srcDir, p.Meta["slug"])},
 76			Summary: &AtomSummary{
 77				Content: fmt.Sprintf("<h2>%s</h2>\n%s",
 78					p.Meta["subtitle"],
 79					string(p.HTML)),
 80				Type: "html",
 81			},
 82		}
 83		entries = append(entries, entry)
 84	}
 85
 86	// 2021-07-14T00:00:00Z
 87	now := time.Now().Format(time.RFC3339)
 88	feed := &AtomFeed{
 89		Xmlns:    "http://www.w3.org/2005/Atom",
 90		Title:    config.Config.Title,
 91		ID:       config.Config.URL,
 92		Subtitle: config.Config.Desc,
 93		Link:     &AtomLink{Href: config.Config.URL},
 94		Author: &AtomAuthor{
 95			Name:  config.Config.Author.Name,
 96			Email: config.Config.Author.Email,
 97		},
 98		Updated: now,
 99		Entries: entries,
100	}
101
102	feedXML, err := xml.MarshalIndent(feed, " ", " ")
103	if err != nil {
104		return nil, err
105	}
106	// Add the <?xml...> header.
107	return []byte(xml.Header + string(feedXML)), nil
108}