From 8e0a307b1198df473a08499af65042865a3248ee Mon Sep 17 00:00:00 2001 From: lyx0 <66651385+lyx0@users.noreply.github.com> Date: Wed, 17 Aug 2022 18:07:50 +0200 Subject: [PATCH] add delete command route for the api --- cmd/api/command.go | 24 ++++++++++++++++++++++++ cmd/api/errors.go | 5 +++++ cmd/api/routes.go | 1 + 3 files changed, 30 insertions(+) diff --git a/cmd/api/command.go b/cmd/api/command.go index 002db60..786bc48 100644 --- a/cmd/api/command.go +++ b/cmd/api/command.go @@ -73,4 +73,28 @@ func (app *application) createCommandHandler(w http.ResponseWriter, r *http.Requ } } +func (app *application) deleteCommandHandler(w http.ResponseWriter, r *http.Request) { + name, err := app.readCommandNameParam(r) + if err != nil { + app.notFoundResponse(w, r) + return + } + + err = app.Models.Commands.Delete(name) + if err != nil { + switch { + case errors.Is(err, data.ErrRecordNotFound): + app.notFoundResponse(w, r) + default: + app.serverErrorResponse(w, r, err) + } + return + } + + err = app.writeJSON(w, http.StatusOK, envelope{"message": fmt.Sprintf("command %s deleted", name)}, nil) + if err != nil { + app.serverErrorResponse(w, r, err) + } +} + type envelope map[string]interface{} diff --git a/cmd/api/errors.go b/cmd/api/errors.go index 8825b5c..f4a7d85 100644 --- a/cmd/api/errors.go +++ b/cmd/api/errors.go @@ -33,3 +33,8 @@ func (app *application) errorResponse(w http.ResponseWriter, r *http.Request, st func (app *application) badRequestResponse(w http.ResponseWriter, r *http.Request, err error) { app.errorResponse(w, r, http.StatusBadRequest, err.Error()) } + +func (app *application) notFoundResponse(w http.ResponseWriter, r *http.Request) { + message := "the requested resource could not be found" + app.errorResponse(w, r, http.StatusNotFound, message) +} diff --git a/cmd/api/routes.go b/cmd/api/routes.go index f79dcd4..20e9ac2 100644 --- a/cmd/api/routes.go +++ b/cmd/api/routes.go @@ -11,5 +11,6 @@ func (app *application) routes() *httprouter.Router { router.HandlerFunc(http.MethodGet, "/v1/commands/:name", app.showCommandHandler) router.HandlerFunc(http.MethodPost, "/v1/commands", app.createCommandHandler) + router.HandlerFunc(http.MethodDelete, "/v1/commands/:name", app.deleteCommandHandler) return router }