From 4f01edb9230f58ff84b0dd892c931ec8ac9aad55 Mon Sep 17 00:00:00 2001 From: Brian Picciano Date: Tue, 13 Sep 2022 12:56:08 +0200 Subject: move src out of srv, clean up default.nix and Makefile --- src/http/feed.go | 77 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 src/http/feed.go (limited to 'src/http/feed.go') diff --git a/src/http/feed.go b/src/http/feed.go new file mode 100644 index 0000000..8bb01c4 --- /dev/null +++ b/src/http/feed.go @@ -0,0 +1,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 + } + }) +} -- cgit v1.2.3