大猩猩mux子路由器空路径

huangapple go评论83阅读模式
英文:

gorilla mux subrouter empty path

问题

我想创建一个如下所示的/user子路由:

user := app.Router.PathPrefix("/user").Subrouter()
user.HandleFunc("/create", (&controllers.User{c}).Create)
user.HandleFunc("", (&controllers.User{c}).Create).Methods("POST")
user.HandleFunc("", (&controllers.User{c}).FindAll).Methods("GET")
user.HandleFunc("/{id}", (&controllers.User{c}).Update).Methods("PUT")
user.HandleFunc("/{id}", (&controllers.User{c}).Destroy).Methods("DELETE")
user.HandleFunc("/{id}", (&controllers.User{c}).FindOne).Methods("GET")

问题是domain/user不起作用。我可以这样做:

user.HandleFunc("/", (&controllers.User{c}).Create).Methods("POST")

但这只匹配domain/user/。有什么办法可以修复这个问题吗?

英文:

i want to create a /user subrouter as following

user := app.Router.PathPrefix("/user").Subrouter()
user.HandleFunc("/create", (&controllers.User{c}).Create)
user.HandleFunc("", (&controllers.User{c}).Create).Methods("POST")
user.HandleFunc("", (&controllers.User{c}).FindAll).Methods("GET")
user.HandleFunc("/{id}", (&controllers.User{c}).Update).Methods("PUT")
user.HandleFunc("/{id}", (&controllers.User{c}).Destroy).Methods("DELETE")
user.HandleFunc("/{id}", (&controllers.User{c}).FindOne).Methods("GET")

the problem is the domain/user doenst work. i can do this

user.HandleFunc("/", (&controllers.User{c}).Create).Methods("POST")

but then it only matches domain/user/
any idea how to fix this

答案1

得分: 0

你可以将路由器的 strict slash 设置为 true,这样 /domain/user 就会重定向到 /domain/user/

你需要在顶部添加以下代码:

<!-- language-all: go -->

app.Router.StrictSlash(true)

并将路由设置为:

user.HandleFunc("/", (&controllers.User{c}).Create).Methods("POST")
user.HandleFunc("/", (&controllers.User{c}).FindAll).Methods("GET")
英文:

You could set the router's strict slash to true so that /domain/user redirects to /domain/user/.

You would need to have at the top:

<!-- language-all: go -->

app.Router.StrictSlash(true)

and set the routes to:

user.HandleFunc(&quot;/&quot;, (&amp;controllers.User{c}).Create).Methods(&quot;POST&quot;)
user.HandleFunc(&quot;/&quot;, (&amp;controllers.User{c}).FindAll).Methods(&quot;GET&quot;)

答案2

得分: 0

如果将strict slash设置为true对你不起作用,那么你可能需要在路由器中处理没有斜杠的路由,而不是使用子路由器:

app.Router.HandleFunc("/user", (&controllers.User{c}).Create).Methods("POST")
app.Router.HandleFunc("/user", (&controllers.User{c}).FindAll).Methods("GET")
英文:

If setting strict slash to true won't work for you, then you may have to handle the routes without a slash in the router rather than using a subrouter:

app.Router.HandleFunc(&quot;/user&quot;, (&amp;controllers.User{c}).Create).Methods(&quot;POST&quot;)
app.Router.HandleFunc(&quot;/user&quot;, (&amp;controllers.User{c}).FindAll).Methods(&quot;GET&quot;)

huangapple
  • 本文由 发表于 2014年7月17日 20:53:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/24804164.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定