diff options
author | Brian Picciano <mediocregopher@gmail.com> | 2022-05-20 07:59:36 -0600 |
---|---|---|
committer | Brian Picciano <mediocregopher@gmail.com> | 2022-05-20 07:59:36 -0600 |
commit | 5a997781871db4c1f504e2f59e14541bb1e62dcb (patch) | |
tree | 7d49a67d3f51660e8f38db10e0cfb473b5db8d36 /srv/src/api/index.go | |
parent | 16f9da05e58043a0944356e5637a18d04c0aa212 (diff) |
Scatter render.go contents everywhere
Diffstat (limited to 'srv/src/api/index.go')
-rw-r--r-- | srv/src/api/index.go | 60 |
1 files changed, 60 insertions, 0 deletions
diff --git a/srv/src/api/index.go b/srv/src/api/index.go new file mode 100644 index 0000000..5fb5a4f --- /dev/null +++ b/srv/src/api/index.go @@ -0,0 +1,60 @@ +package api + +import ( + "fmt" + "net/http" + "path/filepath" + "strings" + + "github.com/mediocregopher/blog.mediocregopher.com/srv/api/apiutil" + "github.com/mediocregopher/blog.mediocregopher.com/srv/post" +) + +func (a *api) renderIndexHandler() http.Handler { + + tpl := a.mustParseBasedTpl("index.html") + const pageCount = 10 + + return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { + + if path := r.URL.Path; !strings.HasSuffix(path, "/") && filepath.Base(path) != "index.html" { + http.Error(rw, "Page not found", 404) + return + } + + page, err := apiutil.StrToInt(r.FormValue("p"), 0) + if err != nil { + apiutil.BadRequest( + rw, r, fmt.Errorf("invalid page number: %w", err), + ) + return + } + + posts, hasMore, err := a.params.PostStore.WithOrderDesc().Get(page, pageCount) + if err != nil { + apiutil.InternalServerError( + rw, r, fmt.Errorf("fetching page %d of posts: %w", page, err), + ) + return + } + + tplPayload := struct { + Posts []post.StoredPost + PrevPage, NextPage int + }{ + Posts: posts, + PrevPage: -1, + NextPage: -1, + } + + if page > 0 { + tplPayload.PrevPage = page - 1 + } + + if hasMore { + tplPayload.NextPage = page + 1 + } + + executeTemplate(rw, r, tpl, tplPayload) + }) +} |