Gorilla Mux同端点多方法路由下GET请求错误码不一致
Gorilla Mux路由匹配异常问题
同一端点添加不同HTTP方法的路由,且各方法配置不同查询参数规则时,GET请求的响应结果出现异常——POST路由的存在影响了GET请求的预期返回。
存在POST路由时
预期返回404,实际得到405
// 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", 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) }
移除POST路由时
返回结果为404
// 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", 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) }
GET请求的路由结果应保持一致,始终返回404。请问是否有人遇到过这个问题?
内容的提问来源于stack exchange,提问作者Ivasan
相关产品推荐
相关产品推荐

