From be06d0a5ca65e1dbc0be352442fcc8ee90c26064 Mon Sep 17 00:00:00 2001 From: lbenedar Date: Thu, 5 Mar 2026 13:20:01 +0300 Subject: [PATCH] ch6.4 --- cmd/web/middleware.go | 18 +++++++++++++++++- cmd/web/routes.go | 2 +- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/cmd/web/middleware.go b/cmd/web/middleware.go index df6000e..d4ffad3 100644 --- a/cmd/web/middleware.go +++ b/cmd/web/middleware.go @@ -1,6 +1,9 @@ package main -import "net/http" +import ( + "fmt" + "net/http" +) func secureHeaders(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -22,3 +25,16 @@ func (app *application) logRequest(next http.Handler) http.Handler { next.ServeHTTP(w, r) }) } + +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, fmt.Errorf("%s", err)) + } + }() + + next.ServeHTTP(w, r) + }) +} diff --git a/cmd/web/routes.go b/cmd/web/routes.go index 9d79b21..99c4dce 100644 --- a/cmd/web/routes.go +++ b/cmd/web/routes.go @@ -12,5 +12,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))) }