Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang, GAE, redirect user?

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, "<HEAD><meta HTTP-EQUIV=\"REFRESH\" content=\"0; url=/one\"></HEAD>")
like image 572
ThePiachu Avatar asked Mar 29 '12 18:03

ThePiachu


2 Answers

For a one-off:

func oneHandler(w http.ResponseWriter, r *http.Request) {
  http.Redirect(w, r, "/one", 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("/one", oneHandler)
  http.HandleFunc("/1", redirectHandler("/one"))
  http.HandleFunc("/two", twoHandler)
  http.HandleFunc("/2", redirectHandler("/two"))
  //etc.
}
like image 157
hyperslug Avatar answered Nov 15 '22 08:11

hyperslug


func handler(rw http.ResponseWriter, ...) {
    rw.SetHeader("Status", "302")
    rw.SetHeader("Location", "/one")
}
like image 28
Hunter Fernandes Avatar answered Nov 15 '22 06:11

Hunter Fernandes