summaryrefslogtreecommitdiff
path: root/srv/src/api/posts.go
diff options
context:
space:
mode:
authorBrian Picciano <mediocregopher@gmail.com>2022-05-14 16:14:11 -0600
committerBrian Picciano <mediocregopher@gmail.com>2022-05-14 17:02:16 -0600
commit4c04177c05355ddb92d3d31a4c5cfbaa86555a13 (patch)
treed40a4dcb70ef84ba9356751a9bd96fed99f7f5d2 /srv/src/api/posts.go
parentdd354bc323cd3176c9676444f99b33b69d0a2062 (diff)
Move template rendering logic into api package
Diffstat (limited to 'srv/src/api/posts.go')
-rw-r--r--srv/src/api/posts.go65
1 files changed, 55 insertions, 10 deletions
diff --git a/srv/src/api/posts.go b/srv/src/api/posts.go
index 995f2fb..cc7a176 100644
--- a/srv/src/api/posts.go
+++ b/srv/src/api/posts.go
@@ -3,11 +3,15 @@ package api
import (
"errors"
"fmt"
+ "html/template"
"net/http"
"path/filepath"
"strings"
- "github.com/mediocregopher/blog.mediocregopher.com/srv/api/apiutils"
+ "github.com/gomarkdown/markdown"
+ "github.com/gomarkdown/markdown/html"
+ "github.com/gomarkdown/markdown/parser"
+ "github.com/mediocregopher/blog.mediocregopher.com/srv/api/apiutil"
"github.com/mediocregopher/blog.mediocregopher.com/srv/post"
)
@@ -22,22 +26,63 @@ func (a *api) postHandler() http.Handler {
http.Error(rw, "Post not found", 404)
return
} else if err != nil {
- apiutils.InternalServerError(
+ apiutil.InternalServerError(
rw, r, fmt.Errorf("fetching post with id %q: %w", id, err),
)
return
}
- renderablePost, err := post.NewRenderablePost(a.params.PostStore, storedPost)
- if err != nil {
- apiutils.InternalServerError(
- rw, r, fmt.Errorf("constructing renderable post with id %q: %w", id, err),
- )
- return
+ parserExt := parser.CommonExtensions | parser.AutoHeadingIDs
+ parser := parser.NewWithExtensions(parserExt)
+
+ htmlFlags := html.CommonFlags | html.HrefTargetBlank
+ htmlRenderer := html.NewRenderer(html.RendererOptions{Flags: htmlFlags})
+
+ renderedBody := markdown.ToHTML([]byte(storedPost.Body), parser, htmlRenderer)
+
+ tplData := struct {
+ post.StoredPost
+ SeriesPrevious, SeriesNext *post.StoredPost
+ Body template.HTML
+ }{
+ StoredPost: storedPost,
+ Body: template.HTML(renderedBody),
+ }
+
+ if series := storedPost.Series; series != "" {
+
+ seriesPosts, err := a.params.PostStore.GetBySeries(series)
+ if err != nil {
+ apiutil.InternalServerError(
+ rw, r,
+ fmt.Errorf("fetching posts for series %q: %w", series, err),
+ )
+ return
+ }
+
+ var foundThis bool
+
+ for i := range seriesPosts {
+
+ seriesPost := seriesPosts[i]
+
+ if seriesPost.ID == storedPost.ID {
+ foundThis = true
+ continue
+ }
+
+ if !foundThis {
+ tplData.SeriesPrevious = &seriesPost
+ continue
+ }
+
+ tplData.SeriesNext = &seriesPost
+ break
+ }
}
- if err := a.params.PostHTTPRenderer.Render(rw, renderablePost); err != nil {
- apiutils.InternalServerError(
+ if err := tpls.ExecuteTemplate(rw, "post.html", tplData); err != nil {
+ apiutil.InternalServerError(
rw, r, fmt.Errorf("rendering post with id %q: %w", id, err),
)
return