diff --git a/cmd/api/middleware.go b/cmd/api/middleware.go new file mode 100644 index 0000000..5052f87 --- /dev/null +++ b/cmd/api/middleware.go @@ -0,0 +1,18 @@ +package main + +import ( + "fmt" + "net/http" +) + +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.serverErrorResponse(w, r, fmt.Errorf("%s", err)) + } + }() + next.ServeHTTP(w, r) + }) +} diff --git a/cmd/api/routes.go b/cmd/api/routes.go index 5acf321..5f79f26 100644 --- a/cmd/api/routes.go +++ b/cmd/api/routes.go @@ -6,7 +6,7 @@ import ( "github.com/julienschmidt/httprouter" ) -func (app *application) routes() *httprouter.Router { +func (app *application) routes() http.Handler { router := httprouter.New() router.NotFound = http.HandlerFunc(app.notFoundResponse) @@ -19,5 +19,6 @@ func (app *application) routes() *httprouter.Router { router.HandlerFunc(http.MethodGet, "/v1/movies/:id", app.showMovieHandler) router.HandlerFunc(http.MethodPatch, "/v1/movies/:id", app.updateMovieHandler) router.HandlerFunc(http.MethodDelete, "/v1/movies/:id", app.deleteMovieHandler) - return router + + return app.recoverPanic(router) }