我的代码看起来像这样
r := mux.NewRouter()
r.Methods("POST").Path("/api1").Handler(...)
r.Methods("GET").Path("/api2").Handler(...)
当我调用GET http://localhost/api1
,GET http://localhost//api1
,POST http://localhost/api2
时,它们可以正常工作。但是我叫POST http://localhost//api2
,它返回错误“405-Method Not Allowed”。这是我的完整代码
首先,我创建默认路由器
func NewDefaultRouter(config RouterConfig) *mux.Router {
router := mux.NewRouter()
writerMW := http_middleware.NewResponseWriterMiddleware()
loggingMW := http_middleware.NewLoggingMiddleware(config.Logger)
metricMW := http_middleware.NewMetricsMiddleware(config.PathMapper)
router.Use(writerMW)
router.Use(loggingMW)
router.Use(metricMW)
}
之后,我为每个http端点添加处理程序 r.Methods("GET").Path("/user/{userID:[0-9]+}").Handler(kithttp.NewServer(
endpoints.GetUser,
decode.GetUserRequest,
pkghttp.EncodeResponse,
options...,
))
r.Methods("POST").Path("/user").Handler(kithttp.NewServer(
endpoints.PostUser,
decode.PostUserRequest,
pkghttp.EncodeResponse,
options...,
))
最佳答案
没有足够的信息来找出为什么您会收到“方法不允许”响应。下面的代码(在线共享的内容)应该可以正常工作
package main
import (
"log"
"net/http"
"github.com/gorilla/mux"
)
func main() {
r := mux.NewRouter()
r.Methods("GET").Path("/user/{userID:[0-9]+}").HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
log.Printf("GET Call")
})
r.Methods("POST").Path("/user").HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
log.Printf("POST Call")
})
http.Handle("/", r)
panic(http.ListenAndServe(":3030", nil))
}
curl -i http://localhost:3030/user/123123
HTTP/1.1 200 OK
Date: Wed, 08 Jul 2020 05:44:17 GMT
Content-Length: 0
curl -i -XPOST http://localhost:3030/user
HTTP/1.1 200 OK
Date: Wed, 08 Jul 2020 05:44:23 GMT
Content-Length: 0
关于go - Gorilla Mux REST api在使用带有双斜杠的POST时给出405错误,但仍在使用GET时有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62773161/