因此,我试图设置我的路由器以响应/users和/users/{userId},所以我尝试了以下代码:
usersRouter := router.PathPrefix("/users").Subrouter()
usersRouter.HandleFunc("", users.GetUsersRoute).Methods("GET")
usersRouter.HandleFunc("/{userId:[0-9]*}", users.GetUserRoute).Methods("GET")问题是,当我转到/users (但确实响应/users/)时,我会得到一个404错误,如果我这样做的话:
router.HandleFunc("/users", users.GetUsersRoute).Methods("GET")
router.HandleFunc("/users/{userId:[0-9]*}", users.GetUserRoute).Methods("GET")它按照我的意愿工作。
有什么方法可以让URL像我想要的那样工作吗?
发布于 2015-04-07 19:58:36
是也不是。通过向路由器添加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因此,如果您的客户是一个浏览器,那么这也许是可以接受的。
https://stackoverflow.com/questions/29482453
复制相似问题