lets-go:6.4 panic recovery

This commit is contained in:
tamsin johnson 2024-01-25 16:02:46 -08:00
parent bee34e7405
commit 2b57596bbc
3 changed files with 16 additions and 2 deletions

View File

@ -15,7 +15,6 @@ func (app *application) home(w http.ResponseWriter, r *http.Request) {
http.NotFound(w, r) http.NotFound(w, r)
return return
} }
snippets, err := app.snippets.Latest() snippets, err := app.snippets.Latest()
if err != nil { if err != nil {
app.serverError(w, r, err) app.serverError(w, r, err)

View File

@ -1,6 +1,7 @@
package main package main
import ( import (
"fmt"
"net/http" "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 { func secureHeaders(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Security-Policy", w.Header().Set("Content-Security-Policy",

View File

@ -16,5 +16,5 @@ func (app *application) routes() http.Handler {
mux.HandleFunc("/snippet/view", app.snippetView) mux.HandleFunc("/snippet/view", app.snippetView)
mux.HandleFunc("/snippet/create", app.snippetCreate) mux.HandleFunc("/snippet/create", app.snippetCreate)
return app.logRequest(secureHeaders(mux)) return app.recoverPanic(app.logRequest(secureHeaders(mux)))
} }