Go 转到:将用户名添加到URL
如何将当前用户的用户名或其他变量添加到Go中URL路径的末尾 我尝试使用http.Redirect(w,“/home/”+user,http.StatusFound),但这将创建一个无限重定向循环 去:Go 转到:将用户名添加到URL,go,Go,如何将当前用户的用户名或其他变量添加到Go中URL路径的末尾 我尝试使用http.Redirect(w,“/home/”+user,http.StatusFound),但这将创建一个无限重定向循环 去: 在这段代码中,我试图将“City”的值附加到根URL的末尾。我应该使用regexp吗?发生这种情况似乎是因为您没有/{city}/处理程序,并且/处理程序正在匹配重定向到城市的所有请求: 模式名称固定的根路径,如“/favicon.ico”,或根子树,如“/images/”(注意后面的斜杠)。较
在这段代码中,我试图将“City”的值附加到根URL的末尾。我应该使用regexp吗?发生这种情况似乎是因为您没有
/{city}/
处理程序,并且/
处理程序正在匹配重定向到城市的所有请求:
模式名称固定的根路径,如“/favicon.ico”,或根子树,如“/images/”(注意后面的斜杠)。较长的模式优先于较短的模式,因此,如果存在为“/images/”和“/images/thumbnails/”注册的处理程序,则将为“/images/thumbnails/”开头的路径调用后一个处理程序,并且前者将接收对“/images/”子树中任何其他路径的请求
请注意,由于以斜杠结尾的模式将根子树命名,因此模式“/”将匹配其他已注册模式未匹配的所有路径,而不仅仅是路径为=“/”的URL
您需要做的是将其放入city url处理程序中,如果您需要处理正则表达式模式,请查看或使用更强大的路由器,如
没有大猩猩怎么办?我知道如何在《大猩猩》中做到这一点,但我只是想知道它在《围棋》中是如何做到的 您可以使用前面提到的答案中提到的自定义处理程序: 要使用此选项,您可以执行以下操作:
import regexp
...
rex := RegexpHandler{}
rex.HandlerFunc(regexp.MustCompile("^/(\w+?)/?"), cityHandler) // cityHandler is your regular handler function
rex.HandlerFunc(regexp.MustCompile("^/"), homeHandler)
http.Handle("/", &rex)
http.ListenAndServe(":8000", nil)
你剩下的代码是什么样子的?路由器和处理程序?添加了上面的代码。你的
/{city}/
URL处理程序在哪里?我没有。我不知道如何使用regexp构造它。过一会儿我会写一个答案谢谢。既然{city}是一个变量,我应该用什么来代替它呢?@user3918985如果你使用的是gorilla的mux
,你可以使用类似的r.handlefun(“/articles/{city}/”,CityHandler)
阅读这里的文档:使用Go Wither gorilla做什么?我知道如何在Gorilla中实现它,但我只是想知道它在Go中是如何实现的。@user3918985我添加了一个如何使用正则表达式处理程序的示例,如果它是您想要的,请接受答案。注意,您还可以在r.HandleFunc(“/articles/{city}/”,CityHandler)
,只需将CityHandler
中的req.URL.Path
拆分为/
<代码>{city}将在拆分[1]
中。
type route struct {
pattern *regexp.Regexp
handler http.Handler
}
type RegexpHandler struct {
routes []*route
}
func (h *RegexpHandler) Handler(pattern *regexp.Regexp, handler http.Handler) {
h.routes = append(h.routes, &route{pattern, handler})
}
func (h *RegexpHandler) HandleFunc(pattern *regexp.Regexp, handler func(http.ResponseWriter, *http.Request)) {
h.routes = append(h.routes, &route{pattern, http.HandlerFunc(handler)})
}
func (h *RegexpHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
for _, route := range h.routes {
if route.pattern.MatchString(r.URL.Path) {
route.handler.ServeHTTP(w, r)
return
}
}
// no pattern matched; send 404 response
http.NotFound(w, r)
}
import regexp
...
rex := RegexpHandler{}
rex.HandlerFunc(regexp.MustCompile("^/(\w+?)/?"), cityHandler) // cityHandler is your regular handler function
rex.HandlerFunc(regexp.MustCompile("^/"), homeHandler)
http.Handle("/", &rex)
http.ListenAndServe(":8000", nil)