Gorilla Mux 子路由方法 POST 请求触发 GET

标签 go gorilla

我正在尝试使用 Gorilla Mux 在 Go 中开发一个简单的 REST API。

我有 ma​​in.go,它注册了上面的简单路径并启动服务器以监听端口 3000。

func main() {
    router := mux.NewRouter().StrictSlash(true)
    sub := router.PathPrefix("/api/v1").Subrouter()
    handlers.RegisterRoutes(sub)

    log.Fatal(http.ListenAndServe(":3000", router))
}

另一个通用 handlers.go 文件中的基本处理程序注册方法

func RegisterRoutes(sub *mux.Router) {
    user.RegisterRoutes(sub)
}

和注册“/user”子路径的user.handler.go文件:

func RegisterRoutes(sub *mux.Router) {
    userRoutes := sub.StrictSlash(true).Path("/users").Subrouter()

    userRoutes.Methods("POST").HandlerFunc(getUsers)
    userRoutes.Methods("GET").HandlerFunc(getUsers)
}

func getUsers(w http.ResponseWriter, r *http.Request) {
    user := User{Name: "test", Password: "test"}

    fmt.Printf("%+v\n", r.Method)

    json.NewEncoder(w).Encode(user)
}

我正在测试我在上面设置的路径,并想出了一个奇怪的行为:

Test - GET - localhost:3000/api/v1/users  => Prints GET in console. (as expected)
Test - GET - localhost:3000/api/v1/users/  => Prints GET in console. (as expected)
Test - POST - localhost:3000/api/v1/users  => Prints POST in console. (as expected)
Test - POST - localhost:3000/api/v1/users/  => Prints GET in console. (And here is the strange behavior)

当我将 POST 发送到端点 (localhost:3000/api/users/) 并在 url 末尾添加尾部斜杠时,它会触发 GET 而不是 POST。

有人在使用 Gorilla Mux 时遇到过这种行为吗?

最佳答案

具体问题是 mux issue 79 ,仍在等待处理(即使已关闭),也见于 mux issue 254

这似乎也与 mux issue 145 有关: StrictSlash 令人困惑

This

"When true, if the route path is "/path/", accessing "/path" will redirect to the former and vice versa. In other words, your application will always see the path as specified in the route."

"When false, if the route path is "/path", accessing "/path/" will not match this route and vice versa."

应该反转,因为 strict==true 应该意味着不允许尾部斜杠。
它的名称和文档令人困惑。

关于Gorilla Mux 子路由方法 POST 请求触发 GET,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46519595/

相关文章:

types - 在 Go 中初始化自定义 int 类型

http - 如何在请求中转义正斜杠以使 url-routers 将其计为 uri 参数的一部分?

Golang gorilla 希望在静态服务中使用尾部斜线

gorilla jsonrpc 得到空响应

Golang “net/http” DetectContentType 错误

datetime - 将 UTC 字符串转换为时间对象

python - 在 Golang 中解密在 Python AES CFB 中加密的内容

performance - 简单网络服务器上的 Golang 高 CPU 使用率无法理解为什么?

session - Golang gorilla session 在重定向后保留表单数据

go - 成功的websocket连接后如何使发送消息到特定的URL?