summaryrefslogtreecommitdiff
path: root/src/http/feed.go
blob: 8bb01c45f67e55b44eee30ca29584d3a9e11d679 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package http

import (
	"fmt"
	"net/http"
	"path/filepath"

	"github.com/gorilla/feeds"
	"github.com/mediocregopher/blog.mediocregopher.com/srv/http/apiutil"
	"github.com/mediocregopher/blog.mediocregopher.com/srv/post"
)

func (a *api) renderFeedHandler() http.Handler {

	return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {

		tag := r.FormValue("tag")

		var (
			posts []post.StoredPost
			err   error
		)

		if tag == "" {
			posts, _, err = a.params.PostStore.Get(0, 20)
		} else {
			posts, err = a.params.PostStore.GetByTag(tag)
		}

		if err != nil {
			apiutil.InternalServerError(rw, r, fmt.Errorf("fetching recent posts: %w", err))
			return
		}

		author := &feeds.Author{
			Name: "mediocregopher",
		}

		publicURL := a.params.PublicURL.String()

		feed := feeds.Feed{
			Title:       "Mediocre Blog",
			Link:        &feeds.Link{Href: publicURL + "/"},
			Description: "A mix of tech, art, travel, and who knows what else.",
			Author:      author,
		}

		for _, post := range posts {

			if post.PublishedAt.After(feed.Updated) {
				feed.Updated = post.PublishedAt
			}

			if post.LastUpdatedAt.After(feed.Updated) {
				feed.Updated = post.LastUpdatedAt
			}

			postURL := publicURL + filepath.Join("/posts", post.ID)

			item := &feeds.Item{
				Title:       post.Title,
				Link:        &feeds.Link{Href: postURL},
				Author:      author,
				Description: post.Description,
				Id:          postURL,
				Created:     post.PublishedAt,
			}

			feed.Items = append(feed.Items, item)
		}

		if err := feed.WriteAtom(rw); err != nil {
			apiutil.InternalServerError(rw, r, fmt.Errorf("writing atom feed: %w", err))
			return
		}
	})
}