go - Gorilla Mux REST api在使用带有双斜杠的POST时给出405错误,但仍在使用GET时有效

标签 go gorilla mux

我的代码看起来像这样

r := mux.NewRouter()
r.Methods("POST").Path("/api1").Handler(...)
r.Methods("GET").Path("/api2").Handler(...)
当我调用GET http://localhost/api1GET http://localhost//api1POST 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/

相关文章:

go - 如何将单个字符转换为单个字节?

string - Go lang 相当于 JavaScript 的 charCode() 方法

generics - 使用泛型的通用 MUX 和 DEMUX

go - 使用 Gorilla MUX 和 Negroni 的子路由中间件

regex - 正则表达式匹配网址路径-Golang与Gorilla Mux

go - 如何创建动态路线

ssl - 在 GoLang 中执行 ReverseProxy 时确认 TLS 证书

rest - Golang 中的动态类型转换

http - 带有静态文件的 Go Gorilla mux 子路由器

session - Gorilla session 包混淆