Golang,GAE,重定向用户?

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

Golang, GAE, redirect user?

问题

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

  1. www.hello.com/1

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

  1. www.hello.com/one

而不是使用:

  1. 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:

  1. www.hello.com/1

I'd want my Go application to redirect the user to:

  1. www.hello.com/one

Without resorting to:

  1. 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

对于一次性的情况:

  1. func oneHandler(w http.ResponseWriter, r *http.Request) {
  2. http.Redirect(w, r, "/one", http.StatusMovedPermanently)
  3. }

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

  1. func redirectHandler(path string) func(http.ResponseWriter, *http.Request) {
  2. return func (w http.ResponseWriter, r *http.Request) {
  3. http.Redirect(w, r, path, http.StatusMovedPermanently)
  4. }
  5. }

并像这样使用它:

  1. func init() {
  2. http.HandleFunc("/one", oneHandler)
  3. http.HandleFunc("/1", redirectHandler("/one"))
  4. http.HandleFunc("/two", twoHandler)
  5. http.HandleFunc("/2", redirectHandler("/two"))
  6. //等等。
  7. }
英文:

For a one-off:

  1. func oneHandler(w http.ResponseWriter, r *http.Request) {
  2. http.Redirect(w, r, &quot;/one&quot;, http.StatusMovedPermanently)
  3. }

If this happens a few times, you can create a redirect handler instead:

  1. func redirectHandler(path string) func(http.ResponseWriter, *http.Request) {
  2. return func (w http.ResponseWriter, r *http.Request) {
  3. http.Redirect(w, r, path, http.StatusMovedPermanently)
  4. }
  5. }

and use it like this:

  1. func init() {
  2. http.HandleFunc(&quot;/one&quot;, oneHandler)
  3. http.HandleFunc(&quot;/1&quot;, redirectHandler(&quot;/one&quot;))
  4. http.HandleFunc(&quot;/two&quot;, twoHandler)
  5. http.HandleFunc(&quot;/2&quot;, redirectHandler(&quot;/two&quot;))
  6. //etc.
  7. }

答案2

得分: 5

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

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

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:

确定