programming

16 How to Understanding HTML Web Redirect in Golang

Redirects

When we create a website, if the user accesses various pages randomly, the page will not be found. So we need to ‘redirect’ a page if the user performs an action on our website page. For example, after logging in, we will redirect to the dashboard page. Redirect itself is actually standard in HTTP and can be seen on the website page https://developer.mozilla.org/en-US/docs/Web/HTTP/Redirections. We only need to create a 3xx response code and add the destination location header. Luckily in Golang there is a function we can use to make this easier.

How to implement it in Golang

OK, we will try to implement HTTP Redirection in Golang. Previously, we first created the two handler functions below.

func RedirectToHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprint(w, "Hello Santekno")
}

func RedirectFromHandler(w http.ResponseWriter, r *http.Request) {
	http.Redirect(w, r, "/redirect-to", http.StatusTemporaryRedirect)
}

After that, we call the handler that we created on the mux router as below.

mux.HandleFunc("/redirect-to", RedirectToHandler)
mux.HandleFunc("/redirect-from", RedirectFromHandler)

Run the program and open the browser by accessing the two pages below.

http://localhost:8080/redirect-to
http://localhost:8080/redirect-from

Then you will see a page like the one below.

tutorial golang redirect

So if we access the redirect-from page then the page will be redirected to redirect-to why is it like that? because in the handler we redirect the page so that it cannot be accessed and redirected to another page.

comments powered by Disqus