所以我尝试设置路由器以响应/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")
它就像我想要的那样。
有没有办法让网址像Subrouters一样工作?
答案 0 :(得分: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, "/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
因此,如果您的客户是浏览器,那么也许这是可以接受的。