Golang,GAE,重定向用户?

The*_*chu 6 html google-app-engine redirect go

如何在GAE上运行Go中重定向页面请求,以便正确显示用户的地址而无需显示重定向页面?例如,如果用户输入:

www.hello.com/1
Run Code Online (Sandbox Code Playgroud)

我希望我的Go应用程序将用户重定向到:

www.hello.com/one
Run Code Online (Sandbox Code Playgroud)

不诉诸:

fmt.Fprintf(w, "<HEAD><meta HTTP-EQUIV=\"REFRESH\" content=\"0; url=/one\"></HEAD>")
Run Code Online (Sandbox Code Playgroud)

hyp*_*lug 22

一次性:

func oneHandler(w http.ResponseWriter, r *http.Request) {
  http.Redirect(w, r, "/one", http.StatusMovedPermanently)
}
Run Code Online (Sandbox Code Playgroud)

如果发生这种情况,您可以创建一个重定向处理程序:

func redirectHandler(path string) func(http.ResponseWriter, *http.Request) { 
  return func (w http.ResponseWriter, r *http.Request) {
    http.Redirect(w, r, path, http.StatusMovedPermanently)
  }
}
Run Code Online (Sandbox Code Playgroud)

并像这样使用它:

func init() {
  http.HandleFunc("/one", oneHandler)
  http.HandleFunc("/1", redirectHandler("/one"))
  http.HandleFunc("/two", twoHandler)
  http.HandleFunc("/2", redirectHandler("/two"))
  //etc.
}
Run Code Online (Sandbox Code Playgroud)


Hun*_*des 5

func handler(rw http.ResponseWriter, ...) {
    rw.SetHeader("Status", "302")
    rw.SetHeader("Location", "/one")
}
Run Code Online (Sandbox Code Playgroud)

  • 对于那些使用Go1的人,不推荐使用`SetHeader`.使用`w.Header().设置("状态","302")`. (5认同)