dongqian1925 2019-03-22 11:17
浏览 12

处理空的Golang大猩猩/ mux var

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")
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
    • ¥500 52810做蓝牙接受端
    • ¥15 基于PLC的三轴机械手程序
    • ¥15 多址通信方式的抗噪声性能和系统容量对比
    • ¥15 winform的chart曲线生成时有凸起
    • ¥15 msix packaging tool打包问题
    • ¥15 finalshell节点的搭建代码和那个端口代码教程
    • ¥15 Centos / PETSc / PETGEM
    • ¥15 centos7.9 IPv6端口telnet和端口监控问题
    • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作