How to Redirect to a URL in Go
The http
package in Go allows you to create an HTTP server to receive HTTP requests and redirect the client to a different URL
Redirecting to a URL in Go is quite easy through the http.Redirect()
method.
It takes an http.ResponseWriter
, *http.Request
, endpoint, and an HTTP status
code as arguments in that order. 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(":6000", mux)
}
You can also utilize 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!