From 2b57596bbc601fa17962d8450af71a4a35b9c122 Mon Sep 17 00:00:00 2001 From: tamsin johnson Date: Thu, 25 Jan 2024 16:02:46 -0800 Subject: [PATCH] lets-go:6.4 panic recovery --- snippetbox/cmd/web/handlers.go | 1 - snippetbox/cmd/web/middleware.go | 15 +++++++++++++++ snippetbox/cmd/web/routes.go | 2 +- 3 files changed, 16 insertions(+), 2 deletions(-) diff --git a/snippetbox/cmd/web/handlers.go b/snippetbox/cmd/web/handlers.go index b574838..bcdcfc7 100644 --- a/snippetbox/cmd/web/handlers.go +++ b/snippetbox/cmd/web/handlers.go @@ -15,7 +15,6 @@ func (app *application) home(w http.ResponseWriter, r *http.Request) { http.NotFound(w, r) return } - snippets, err := app.snippets.Latest() if err != nil { app.serverError(w, r, err) diff --git a/snippetbox/cmd/web/middleware.go b/snippetbox/cmd/web/middleware.go index 5a4e7e3..b25aeda 100644 --- a/snippetbox/cmd/web/middleware.go +++ b/snippetbox/cmd/web/middleware.go @@ -1,6 +1,7 @@ package main import ( + "fmt" "net/http" ) @@ -19,6 +20,20 @@ func (app *application) logRequest(next http.Handler) http.Handler { }) } +// recoverPanic ... +func (app *application) recoverPanic(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + defer func() { + if err := recover(); err != nil { + w.Header().Set("Connection", "close") + app.serverError(w, r, fmt.Errorf("%s", err)) + } + }() + + next.ServeHTTP(w, r) + }) +} + func secureHeaders(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Security-Policy", diff --git a/snippetbox/cmd/web/routes.go b/snippetbox/cmd/web/routes.go index 7736217..9badce3 100644 --- a/snippetbox/cmd/web/routes.go +++ b/snippetbox/cmd/web/routes.go @@ -16,5 +16,5 @@ func (app *application) routes() http.Handler { mux.HandleFunc("/snippet/view", app.snippetView) mux.HandleFunc("/snippet/create", app.snippetCreate) - return app.logRequest(secureHeaders(mux)) + return app.recoverPanic(app.logRequest(secureHeaders(mux))) }