go - negroni/gorilla mux 的子路由器问题

标签 go gorilla negroni

所以我正在尝试设置我的路由器以响应 /users/users/{userId} 所以我尝试了这段代码:

usersRouter := router.PathPrefix("/users").Subrouter()
usersRouter.HandleFunc("", users.GetUsersRoute).Methods("GET")
usersRouter.HandleFunc("/{userId:[0-9]*}", users.GetUserRoute).Methods("GET")

问题是当我转到 /users 时出现 404 错误(但确实响应 /users/)如果我这样做:

router.HandleFunc("/users", users.GetUsersRoute).Methods("GET")
router.HandleFunc("/users/{userId:[0-9]*}", users.GetUserRoute).Methods("GET")

它像我想要的那样工作。

有什么方法可以让 URL 像我希望的那样使用 Subrouter 工作吗?

最佳答案

是也不是。您可以通过向路由器添加 StrictSlash(true) 使路由半工作。

给定以下代码

package main

    import (
        "fmt"
        "net/http"

        "github.com/gorilla/mux"
    )

    func main() {
        mainRouter := mux.NewRouter().StrictSlash(true)
        mainRouter.HandleFunc("/test", func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "test") })

        subRouter := mainRouter.PathPrefix("/users").Subrouter()
        subRouter.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "/users") })
        subRouter.HandleFunc("/{id:[0-9]+}", func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "/users/id") })
        http.ListenAndServe(":8080", mainRouter)
    }

请求http://localhost:8080/users会回来的

< HTTP/1.1 301 Moved Permanently
< Location: /users/
< Date: Tue, 07 Apr 2015 19:52:12 GMT
< Content-Length: 42
< Content-Type: text/html; charset=utf-8
< 
<a href="/users/">Moved Permanently</a>.

请求http://localhost:8080/users/返回

< HTTP/1.1 200 OK
< Date: Tue, 07 Apr 2015 19:54:43 GMT
< Content-Length: 6
< Content-Type: text/plain; charset=utf-8

< /users

因此,如果您的客户端是浏览器,那么这也许是可以接受的。

关于go - negroni/gorilla mux 的子路由器问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29482453/

相关文章:

docker - 如何处理 make missing from alpine docker image?

go - axios 不发送 POST 到 golang api

go - 用于公共(public)和私有(private)路由中间件的 httprouter 和 negroni

angularjs - 没有 urlRouterProvider.otherwise 的 ui 路由

web-applications - Go Gorilla mux 来处理 API 请求

go - header 已经写好了。想要用500覆盖状态码200

go - 如何在golang中解码编码的HTTP header

go - Go 之旅 #23 : weird behaviour with return

go - 混合:= and = in Go if statements