diff options
author | Brian Picciano <mediocregopher@gmail.com> | 2022-05-14 17:02:30 -0600 |
---|---|---|
committer | Brian Picciano <mediocregopher@gmail.com> | 2022-05-14 17:02:30 -0600 |
commit | e41ff2b897be24a894e75b850f1c06652cc034be (patch) | |
tree | 816cc87b789dd96b60f212311e161af1bb583e6a /srv/src/api/posts.go | |
parent | 4c04177c05355ddb92d3d31a4c5cfbaa86555a13 (diff) |
Implement index handler
This involved re-arranging how templates are being parsed, slightly.
Diffstat (limited to 'srv/src/api/posts.go')
-rw-r--r-- | srv/src/api/posts.go | 91 |
1 files changed, 0 insertions, 91 deletions
diff --git a/srv/src/api/posts.go b/srv/src/api/posts.go deleted file mode 100644 index cc7a176..0000000 --- a/srv/src/api/posts.go +++ /dev/null @@ -1,91 +0,0 @@ -package api - -import ( - "errors" - "fmt" - "html/template" - "net/http" - "path/filepath" - "strings" - - "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" -) - -func (a *api) postHandler() http.Handler { - return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { - - id := strings.TrimSuffix(filepath.Base(r.URL.Path), ".html") - - storedPost, err := a.params.PostStore.GetByID(id) - - if errors.Is(err, post.ErrPostNotFound) { - http.Error(rw, "Post not found", 404) - return - } else if err != nil { - apiutil.InternalServerError( - rw, r, fmt.Errorf("fetching 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 := tpls.ExecuteTemplate(rw, "post.html", tplData); err != nil { - apiutil.InternalServerError( - rw, r, fmt.Errorf("rendering post with id %q: %w", id, err), - ) - return - } - }) -} |