Golang, gae, redirect user?

How can I redirect a page request to Go running in GAE so that the user address is displayed correctly without having to display the redirect page? For example, if the user enters:

www.hello.com/1 

I want my Go application to redirect the user:

 www.hello.com/one 

Without resorting to:

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

For single use:

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

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

 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 as follows:

 func init() { http.HandleFunc("/one", oneHandler) http.HandleFunc("/1", redirectHandler("/one")) http.HandleFunc("/two", twoHandler) http.HandleFunc("/2", redirectHandler("/two")) //etc. } 
+22
source
 func handler(rw http.ResponseWriter, ...) { rw.SetHeader("Status", "302") rw.SetHeader("Location", "/one") } 
+5
source

Source: https://habr.com/ru/post/911971/


All Articles