add delete command route for the api

This commit is contained in:
lyx0 2022-08-17 18:07:50 +02:00
parent e9438d3b21
commit 8e0a307b11
3 changed files with 30 additions and 0 deletions

View file

@ -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{}

View file

@ -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)
}

View file

@ -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
}