2015-04-07 37 views
0

所以我想设置我的路由器,为/users/users/{userId}回应,所以我尝试此代码:与内格罗尼/大猩猩MUX Subrouter问题

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

的问题是,我得到一个404错误,当我去/users(但不以/users/响应)如果我做的:

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

它像我想它。

有什么办法让网址像我想要的那样工作吗?

回答

1

是和否。您可以通过将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, "https://stackoverflow.com/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="https://stackoverflow.com/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 

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