From 661a30542b697df62e45161a69e893e2fe6cfeb8 Mon Sep 17 00:00:00 2001 From: lyx0 <66651385+lyx0@users.noreply.github.com> Date: Wed, 17 Aug 2022 23:14:05 +0200 Subject: [PATCH] add NotFound and MethodNotAllowed routes --- cmd/api/errors.go | 9 ++++++--- cmd/api/routes.go | 3 +++ 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/cmd/api/errors.go b/cmd/api/errors.go index d5be1ff..5dd46c0 100644 --- a/cmd/api/errors.go +++ b/cmd/api/errors.go @@ -12,9 +12,7 @@ func (app *application) serverErrorResponse(w http.ResponseWriter, r *http.Reque app.errorResponse(w, r, http.StatusInternalServerError, message) } -// The logError() method is a generic helper for logging an error message. Later in the -// book we'll upgrade this to use structured logging, and record additional information -// about the request including the HTTP method and URL. +// The logError() method is a generic helper for logging an error message. func (app *application) logError(r *http.Request, err error) { app.Logger.Errorw("Error", "Request URI", r.RequestURI, @@ -43,3 +41,8 @@ func (app *application) editConflictResponse(w http.ResponseWriter, r *http.Requ message := "unable to update the record due to an edit conflict, please try again" app.errorResponse(w, r, http.StatusConflict, message) } + +func (app *application) methodNotAllowedResponse(w http.ResponseWriter, r *http.Request) { + message := fmt.Sprintf("the %s method is not supported for this resource", r.Method) + app.errorResponse(w, r, http.StatusMethodNotAllowed, message) +} diff --git a/cmd/api/routes.go b/cmd/api/routes.go index 5259ca7..c2ab691 100644 --- a/cmd/api/routes.go +++ b/cmd/api/routes.go @@ -9,6 +9,9 @@ import ( func (app *application) routes() *httprouter.Router { router := httprouter.New() + router.NotFound = http.HandlerFunc(app.notFoundResponse) + router.MethodNotAllowed = http.HandlerFunc(app.methodNotAllowedResponse) + router.HandlerFunc(http.MethodGet, "/v1/commands/:name", app.showCommandHandler) router.HandlerFunc(http.MethodPost, "/v1/commands", app.createCommandHandler) router.HandlerFunc(http.MethodPatch, "/v1/commands/:name", app.updateCommandHandler)