gorilla/mux

[bug] Adding to GET the same endpoint with POST and different Queries ends up with inconsistent error messages

Ivasan7 opened this issue · 0 comments

Describe the bug
Adding the same endpoint POST with different Queries ends up with incosnsistent error messages

Versions
Go version: 1.18

Steps to Reproduce
Playground: https://go.dev/play/p/xzoAkpEhGgy

// You can edit this code!
// Click here and start typing.
package main

import (
	"encoding/json"
	"fmt"
	"net/http"
	"net/http/httptest"
	"time"

	"github.com/gorilla/mux"
)

func main() {

	r := mux.NewRouter()

	r.HandleFunc("/api/v2", func(w http.ResponseWriter, r *http.Request) {
		// an example API handler
		fmt.Fprintf(w, "You made a POST request")
		json.NewEncoder(w).Encode(map[string]bool{"ok": true})
	}).Methods("POST")

	r.HandleFunc("/api/v2", func(w http.ResponseWriter, r *http.Request) {
		// an example API handler
		fmt.Fprintf(w, "You made a GET request")
		json.NewEncoder(w).Encode(map[string]bool{"ok": true})
	}).
		Queries("from", "{from:[0-9]+}",
			"to", "{to:[0-9]+}").Methods("GET")


	srv := &http.Server{
		Handler: r,
		Addr:    "127.0.0.1:8000",
		// Good practice: enforce timeouts for servers you create!
		WriteTimeout: 15 * time.Second,
		ReadTimeout:  15 * time.Second,
	}
	go srv.ListenAndServe()


	req2 := httptest.NewRequest("GET", "/api/v2?from=3&to=-5", nil)
	out2 := httptest.NewRecorder()

	r.ServeHTTP(out2, req2)

	fmt.Println(out2.Code)
	fmt.Println(out2)

}

ENDS with the result, I was expecting 404:

405

HOWEVER

When I remove the POST request
playground: https://go.dev/play/p/EXiF00_WrFW

// You can edit this code!
// Click here and start typing.
package main

import (
	"encoding/json"
	"fmt"
	"net/http"
	"net/http/httptest"
	"time"

	"github.com/gorilla/mux"
)

func main() {

	r := mux.NewRouter()

	r.HandleFunc("/api/v2", func(w http.ResponseWriter, r *http.Request) {
		// an example API handler
		fmt.Fprintf(w, "You made a GET request")
		json.NewEncoder(w).Encode(map[string]bool{"ok": true})
	}).
		Queries("from", "{from:[0-9]+}",
			"to", "{to:[0-9]+}").Methods("GET")


	srv := &http.Server{
		Handler: r,
		Addr:    "127.0.0.1:8000",
		// Good practice: enforce timeouts for servers you create!
		WriteTimeout: 15 * time.Second,
		ReadTimeout:  15 * time.Second,
	}
	go srv.ListenAndServe()


	req2 := httptest.NewRequest("GET", "/api/v2?from=3&to=-5", nil)
	out2 := httptest.NewRecorder()

	r.ServeHTTP(out2, req2)

	fmt.Println(out2.Code)

}

Result is

 404

Expected behavior
Both cases should end in only 404-s