【问题标题】:Golang, GAE, redirect user?Golang,GAE,重定向用户?
【发布时间】:2012-03-29 18:59:42
【问题描述】:

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

www.hello.com/1

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

www.hello.com/one

不诉诸于:

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

【问题讨论】:

    标签: html google-app-engine redirect go


    【解决方案1】:

    一次性:

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

    【讨论】:

      【解决方案2】:
      func handler(rw http.ResponseWriter, ...) {
          rw.SetHeader("Status", "302")
          rw.SetHeader("Location", "/one")
      }
      

      【讨论】:

      • 对于使用 Go1 的用户,SetHeader 已弃用。请改用w.Header().Set("Status","302")
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-22
      • 2011-07-24
      • 2015-04-10
      • 2020-07-02
      • 2013-06-21
      • 2016-12-01
      相关资源
      最近更新 更多