diff options
author | Alan Pearce | 2024-06-24 21:49:00 +0200 |
---|---|---|
committer | Alan Pearce | 2024-06-24 23:09:15 +0200 |
commit | 49b4d4d4e2bfcb5152b574100755bfbd39ede602 (patch) | |
tree | 39dc87b6309bf227cf4211e2418af5faff0447fc | |
parent | a2feb8c63c80a1f52830f562af2deb2c6065eaae (diff) | |
download | website-49b4d4d4e2bfcb5152b574100755bfbd39ede602.tar.lz website-49b4d4d4e2bfcb5152b574100755bfbd39ede602.tar.zst website-49b4d4d4e2bfcb5152b574100755bfbd39ede602.zip |
make 404 page dynamic
-rw-r--r-- | internal/website/mux.go | 22 |
1 files changed, 17 insertions, 5 deletions
diff --git a/internal/website/mux.go b/internal/website/mux.go index 4cc013e..df58ee5 100644 --- a/internal/website/mux.go +++ b/internal/website/mux.go @@ -7,6 +7,7 @@ import ( "strings" "website/internal/config" "website/internal/log" + "website/templates" "github.com/benpate/digit" "github.com/kevinpollet/nego" @@ -32,18 +33,29 @@ func canonicalisePath(path string) (cPath string, differs bool) { type webHandler func(http.ResponseWriter, *http.Request) *HTTPError -func (fn webHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { +type WrappedWebHandler struct { + config *config.Config + handler webHandler +} + +func wrapHandler(cfg *config.Config, webHandler webHandler) WrappedWebHandler { + return WrappedWebHandler{ + config: cfg, + handler: webHandler, + } +} + +func (fn WrappedWebHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { defer func() { if fail := recover(); fail != nil { w.WriteHeader(http.StatusInternalServerError) log.Error("runtime panic!", "error", fail) } }() - if err := fn(w, r); err != nil { + if err := fn.handler(w, r); err != nil { if strings.Contains(r.Header.Get("Accept"), "text/html") { w.WriteHeader(err.Code) - notFoundPage := "website/private/404.html" - http.ServeFile(w, r, notFoundPage) + templates.NotFound(*fn.config, r.URL.Path).Render(r.Context(), w) } else { http.Error(w, err.Message, err.Code) } @@ -60,7 +72,7 @@ func NewMux(cfg *config.Config, root string) (mux *http.ServeMux, err error) { return nil, errors.WithMessagef(err, "registering content files") } - mux.Handle("/", webHandler(func(w http.ResponseWriter, r *http.Request) *HTTPError { + mux.Handle("/", wrapHandler(cfg, func(w http.ResponseWriter, r *http.Request) *HTTPError { urlPath, shouldRedirect := canonicalisePath(r.URL.Path) if shouldRedirect { http.Redirect(w, r, urlPath, 302) |