英文:
Golang, GAE, redirect user?
问题
如何在运行在GAE上的Go中重定向页面请求,以便用户的地址能正确显示,而不需要显示重定向页面?例如,如果用户输入:
www.hello.com/1
我希望我的Go应用程序将用户重定向到:
www.hello.com/one
而不是使用:
fmt.Fprintf(w, "<HEAD><meta HTTP-EQUIV=\"REFRESH\" content=\"0; url=/one\"></HEAD>")
英文:
How can I redirect a page request in Go running on GAE, so that the user's address would display correctly without resorting to displaying a redirection page? For example, if user would type:
www.hello.com/1
I'd want my Go application to redirect the user to:
www.hello.com/one
Without resorting to:
fmt.Fprintf(w, "<HEAD><meta HTTP-EQUIV=\"REFRESH\" content=\"0; url=/one\"></HEAD>")
答案1
得分: 22
对于一次性的情况:
func oneHandler(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/one", http.StatusMovedPermanently)
}
如果这种情况发生几次,你可以创建一个重定向处理程序:
func redirectHandler(path string) func(http.ResponseWriter, *http.Request) {
return func (w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, path, http.StatusMovedPermanently)
}
}
并像这样使用它:
func init() {
http.HandleFunc("/one", oneHandler)
http.HandleFunc("/1", redirectHandler("/one"))
http.HandleFunc("/two", twoHandler)
http.HandleFunc("/2", redirectHandler("/two"))
//等等。
}
英文:
For a one-off:
func oneHandler(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/one", http.StatusMovedPermanently)
}
If this happens a few times, you can create a redirect handler instead:
func redirectHandler(path string) func(http.ResponseWriter, *http.Request) {
return func (w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, path, http.StatusMovedPermanently)
}
}
and use it like this:
func init() {
http.HandleFunc("/one", oneHandler)
http.HandleFunc("/1", redirectHandler("/one"))
http.HandleFunc("/two", twoHandler)
http.HandleFunc("/2", redirectHandler("/two"))
//etc.
}
答案2
得分: 5
func handler(rw http.ResponseWriter, ...) {
rw.SetHeader("状态", "302")
rw.SetHeader("位置", "/one")
}
英文:
func handler(rw http.ResponseWriter, ...) {
rw.SetHeader("Status", "302")
rw.SetHeader("Location", "/one")
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论