Golang,GAE,重定向用户?

huangapple go评论102阅读模式
英文:

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, &quot;&lt;HEAD&gt;&lt;meta HTTP-EQUIV=\&quot;REFRESH\&quot; content=\&quot;0; url=/one\&quot;&gt;&lt;/HEAD&gt;&quot;)

答案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, &quot;/one&quot;, 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(&quot;/one&quot;, oneHandler)
  http.HandleFunc(&quot;/1&quot;, redirectHandler(&quot;/one&quot;))
  http.HandleFunc(&quot;/two&quot;, twoHandler)
  http.HandleFunc(&quot;/2&quot;, redirectHandler(&quot;/two&quot;))
  //etc.
}

答案2

得分: 5

func handler(rw http.ResponseWriter, ...) {
rw.SetHeader("状态", "302")
rw.SetHeader("位置", "/one")
}

英文:
func handler(rw http.ResponseWriter, ...) {
    rw.SetHeader(&quot;Status&quot;, &quot;302&quot;)
    rw.SetHeader(&quot;Location&quot;, &quot;/one&quot;)
}

huangapple
  • 本文由 发表于 2012年3月30日 02:59:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/9931708.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定