summaryrefslogtreecommitdiff
path: root/src/http/feed.go
blob: eb724642a5889875b13fe9dc0afd5556521259b9 (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
package http

import (
	"fmt"
	"net/http"

	"github.com/gorilla/feeds"
	"dev.mediocregopher.com/mediocre-blog.git/src/http/apiutil"
	"dev.mediocregopher.com/mediocre-blog.git/src/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:  "mediocregopher's lil web corner",
			Link:   &feeds.Link{Href: publicURL + "/"},
			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 := a.postURL(post.ID, true)

			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
		}
	})
}