diff options
author | Brian Picciano <mediocregopher@gmail.com> | 2022-05-20 17:24:52 -0600 |
---|---|---|
committer | Brian Picciano <mediocregopher@gmail.com> | 2022-05-20 17:24:52 -0600 |
commit | 99f8c1188ccd1580f58ad4c21cece040ed8e874c (patch) | |
tree | 1c4389da9129a9e7201ae6d4ad00e48c15e55170 /srv/src/http/feed.go | |
parent | b4ca8853a9085cb0231f2c4de25a1ec07ef150a0 (diff) |
Add RSS feed generator
Diffstat (limited to 'srv/src/http/feed.go')
-rw-r--r-- | srv/src/http/feed.go | 63 |
1 files changed, 63 insertions, 0 deletions
diff --git a/srv/src/http/feed.go b/srv/src/http/feed.go new file mode 100644 index 0000000..8c0ef1c --- /dev/null +++ b/srv/src/http/feed.go @@ -0,0 +1,63 @@ +package http + +import ( + "fmt" + "net/http" + "path/filepath" + + "github.com/gorilla/feeds" + "github.com/mediocregopher/blog.mediocregopher.com/srv/http/apiutil" +) + +func (a *api) renderFeedHandler() http.Handler { + + return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { + + 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, + } + + recentPosts, _, err := a.params.PostStore.WithOrderDesc().Get(0, 20) + if err != nil { + apiutil.InternalServerError(rw, r, fmt.Errorf("fetching recent posts: %w", err)) + return + } + + for _, post := range recentPosts { + + 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) + + feed.Items = append(feed.Items, &feeds.Item{ + Title: post.Title, + Link: &feeds.Link{Href: postURL}, + Author: author, + Description: post.Description, + Id: postURL, + Updated: post.LastUpdatedAt, + Created: post.PublishedAt, + }) + } + + if err := feed.WriteAtom(rw); err != nil { + apiutil.InternalServerError(rw, r, fmt.Errorf("writing atom feed: %w", err)) + return + } + }) +} |