I have the following controller function that is supposed to delete an item within a collection. I am using the gorilla/mux
package. The problem arises when I try to handle the case where the user forgot to send an id on a DELETE request.
localhost:8000/movies/
or localhost:8000/movies
While an example of the proper request would be
localhost:8000/movies/3
Although params["id"]
is empty, the execution never goes into the else block. I am not sure why.
func (c Controller) Delete(db *sql.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var error Error
params := mux.Vars(r)
movieRepo := movieRepo.MovieRepository{}
if _, ok := params["id"]; ok {
id, err := strconv.Atoi(params["id"])
if err != nil {
error.Message = "Server error"
utils.SendError(w, http.StatusInternalServerError, error)
return
}
rowsDeleted, err := movieRepo.delete(db, id)
w.Header().Set("Content-Type", "text/plain")
successMessage(w, rowsDeleted)
} else {
fmt.Println("errrr..")
error.Message = "Id is not present."
errorMessage(w, http.StatusBadRequest, error)
return
}
}
}
EDIT
This is how the endpoint is registered on the router:
router.HandleFunc("/movies/{id}",controller.Delete(db)).Methods("DELETE")