From 09acb111a2b22f5794541fac175b024dd0f9100e Mon Sep 17 00:00:00 2001 From: Brian Picciano Date: Fri, 20 May 2022 11:17:31 -0600 Subject: Rename api package to http --- srv/src/http/index.go | 60 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 srv/src/http/index.go (limited to 'srv/src/http/index.go') diff --git a/srv/src/http/index.go b/srv/src/http/index.go new file mode 100644 index 0000000..bb76568 --- /dev/null +++ b/srv/src/http/index.go @@ -0,0 +1,60 @@ +package http + +import ( + "fmt" + "net/http" + "path/filepath" + "strings" + + "github.com/mediocregopher/blog.mediocregopher.com/srv/http/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) + }) +} -- cgit v1.2.3