2015-04-07 76 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 

因此,如果您的客戶端是一個瀏覽器那麼也許這可以接受。