From 4c04177c05355ddb92d3d31a4c5cfbaa86555a13 Mon Sep 17 00:00:00 2001 From: Brian Picciano Date: Sat, 14 May 2022 16:14:11 -0600 Subject: Move template rendering logic into api package --- srv/src/api/posts.go | 65 ++++++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 55 insertions(+), 10 deletions(-) (limited to 'srv/src/api/posts.go') 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 -- cgit v1.2.3