I'm trying to develop a simple REST API in Go, using Gorilla Mux.
I have the main.go which register the simple path above and start the server to listen on port 3000.
func main() {
router := mux.NewRouter().StrictSlash(true)
sub := router.PathPrefix("/api/v1").Subrouter()
handlers.RegisterRoutes(sub)
log.Fatal(http.ListenAndServe(":3000", router))
}
A basic handlers registration method inside another generic handlers.go file
func RegisterRoutes(sub *mux.Router) {
user.RegisterRoutes(sub)
}
And the user.handler.go file, which register the "/user" subroute:
func RegisterRoutes(sub *mux.Router) {
userRoutes := sub.StrictSlash(true).Path("/users").Subrouter()
userRoutes.Methods("POST").HandlerFunc(getUsers)
userRoutes.Methods("GET").HandlerFunc(getUsers)
}
func getUsers(w http.ResponseWriter, r *http.Request) {
user := User{Name: "test", Password: "test"}
fmt.Printf("%+v
", r.Method)
json.NewEncoder(w).Encode(user)
}
I was testing the path that I've had set up above, and came up with an wird behavior:
Test - GET - localhost:3000/api/v1/users => Prints GET in console. (as expected) Test - GET - localhost:3000/api/v1/users/ => Prints GET in console. (as expected) Test - POST - localhost:3000/api/v1/users => Prints POST in console. (as expected) Test - POST - localhost:3000/api/v1/users/ => Prints GET in console. (And here is the strange behavior)
When I send a POST to the endpoint(localhost:3000/api/users/) with the trailing slash at the end of the url it triggers the GET instead of the POST.
Anyone came across with this behavior using Gorilla Mux?