英文:
How to call a route by its name from inside a handler?
问题
如何在处理程序内正确引用路由名称?
mux.NewRouter()
应该全局分配,而不是在函数内部定义。
func AnotherHandler(writer http.ResponseWriter, req *http.Request) {
url, _ := r.Get("home") // 我假设这里的 'r' 是指路由器
http.Redirect(writer, req, url, 302)
}
func main() {
r := mux.NewRouter()
r.HandleFunc("/", HomeHandler).Name("home")
r.HandleFunc("/nothome/", AnotherHandler).Name("another")
http.Handle("/", r)
http.ListenAndServe(":8000", nil)
}
英文:
How do I properly refer to route names from inside handlers?
Should mux.NewRouter()
be assigned globally instead of standing inside a function?
func AnotherHandler(writer http.ResponseWriter, req *http.Request) {
url, _ := r.Get("home") // I suppose this 'r' should refer to the router
http.Redirect(writer, req, url, 302)
}
func main() {
r := mux.NewRouter()
r.HandleFunc("/", HomeHandler).Name("home")
r.HandleFunc("/nothome/", AnotherHandler).Name("another")
http.Handle("/", r)
http.ListenAndServe(":8000", nil)
}
答案1
得分: 8
你有一个名为mux.CurrentRoute()
的方法,它返回给定请求的路由。通过该请求,你可以创建一个子路由并调用Get("home")
。
示例:(play: http://play.golang.org/p/Lz10YUyP6e)
package main
import (
"fmt"
"net/http"
"github.com/gorilla/mux"
)
func HomeHandler(writer http.ResponseWriter, req *http.Request) {
writer.WriteHeader(200)
fmt.Fprintf(writer, "Home!!!\n")
}
func AnotherHandler(writer http.ResponseWriter, req *http.Request) {
url, err := mux.CurrentRoute(req).Subrouter().Get("home").URL()
if err != nil {
panic(err)
}
http.Redirect(writer, req, url.String(), 302)
}
func main() {
r := mux.NewRouter()
r.HandleFunc("/home", HomeHandler).Name("home")
r.HandleFunc("/nothome/", AnotherHandler).Name("another")
http.Handle("/", r)
http.ListenAndServe(":8000", nil)
}
英文:
You have the method mux.CurrentRoute()
that returns the route for a given request. From that request, you can create a subrouter and call Get("home")
Example: (play: http://play.golang.org/p/Lz10YUyP6e)
package main
import (
"fmt"
"net/http"
"github.com/gorilla/mux"
)
func HomeHandler(writer http.ResponseWriter, req *http.Request) {
writer.WriteHeader(200)
fmt.Fprintf(writer, "Home!!!\n")
}
func AnotherHandler(writer http.ResponseWriter, req *http.Request) {
url, err := mux.CurrentRoute(req).Subrouter().Get("home").URL()
if err != nil {
panic(err)
}
http.Redirect(writer, req, url.String(), 302)
}
func main() {
r := mux.NewRouter()
r.HandleFunc("/home", HomeHandler).Name("home")
r.HandleFunc("/nothome/", AnotherHandler).Name("another")
http.Handle("/", r)
http.ListenAndServe(":8000", nil)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论