我正在尝试使用 Gorilla Mux 在 Go 中开发一个简单的 REST API。
我有 main.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/