How to Redirect to a URL in Go
Redirecting to a URL in Go is done through the http.Redirect()
method. It
accepts an http.ResponseWriter
, *http.Request
, endpoint, and
HTTP status code as arguments in that order.
func Redirect(w ResponseWriter, r *Request, url string, code int)
Here’s how to use it:
func redirectToFreshman(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "https://freshman.tech", http.StatusSeeOther)
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/", redirectToFreshman)
http.ListenAndServe(":8080", mux)
}
You can also use the http.RedirectHandler()
method to avoid creating another
function:
func main() {
mux := http.NewServeMux()
mux.Handle("/", http.RedirectHandler("https://freshman.tech", http.StatusSeeOther))
http.ListenAndServe(":6000", mux)
}
Thanks for reading, and happy coding!