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>")
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.
}
func handler(rw http.ResponseWriter, ...) {
rw.SetHeader("Status", "302")
rw.SetHeader("Location", "/one")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With