dongzhi4073
2019-05-20 20:32 阅读 45
已采纳

为什么我在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 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.

    点赞 评论 复制链接分享

相关推荐