如何在Go上运行的GAE中重定向页面请求,以便正确显示用户的地址而无需显示重定向页面?例如,如果用户输入:
www.hello.com/1
我希望我的Go应用程序将用户重定向到:
www.hello.com/one
不诉诸:
fmt.Fprintf(w, "<HEAD><meta HTTP-EQUIV=\"REFRESH\" content=\"0; url=/one\"></HEAD>")
答案 0 :(得分: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"))
//etc.
}
答案 1 :(得分:5)
func handler(rw http.ResponseWriter, ...) {
rw.SetHeader("Status", "302")
rw.SetHeader("Location", "/one")
}