dongzhi4073 2019-05-20 20:32
浏览 46
已采纳

为什么我在GET之后放置DELETE路由器,但未触发DELETE端点

I was creating restful API with Golang and I put the delete router after the getOne router by index, and the delete router never got triggered? I don't know why? When I reverse them, it works! Can someone know the reason??

This is for Building Restful API with Golang.

Not works:

myRouter.HandleFunc("/article", createNewArticle).Methods("POST")

myRouter.HandleFunc("/article/{id}", getOneArticle)

myRouter.HandleFunc("/article/{id}", deleteArticle).Methods("DELETE")

Works!

myRouter.HandleFunc("/article", createNewArticle).Methods("POST")
myRouter.HandleFunc("/article/{id}", deleteArticle).Methods("DELETE")
myRouter.HandleFunc("/article/{id}", getOneArticle)

When I test the api using postman with DELETE methods, it always trigger the getOneArticle and respond with the delete item, but did not actually delete in the database!

  • 写回答

1条回答 默认 最新

  • dsj0312 2019-05-21 00:36
    关注

    You're using gorilla/mux. When an HTTP request comes in, this router tries to match routes in the order in which you add them.

    When you add the route without specifying an HTTP method, it applies to all HTTP methods.

    So, if your more specific route matching the DELETE method comes first, then it will match DELETE method calls, and the next route will match all methods. While it would match DELETE also, an actual DELETE call would never reach it because of the route preceding it.

    But if you reverse them, the route which doesn't specify an HTTP method will match all methods, including DELETE.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料