Search code examples
gogorilla

Why I put the DELETE router after GET, the DELETE endpoint did not get triggered


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!


Solution

  • 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.