You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 05:35:22