Skip to content

Instantly share code, notes, and snippets.

@hSATAC
Created April 9, 2013 05:38
Show Gist options
  • Save hSATAC/5343225 to your computer and use it in GitHub Desktop.
Save hSATAC/5343225 to your computer and use it in GitHub Desktop.
Http Redirect in Golang
package main
import (
"log"
"net/http"
)
func redirect(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "http://www.google.com", 301)
}
func main() {
http.HandleFunc("/", redirect)
err := http.ListenAndServe(":9090", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
@donatj
Copy link

donatj commented Feb 17, 2021

You can skip the middle man and go:

http.HandleFunc("/", http.RedirectHandler("http://www.google.com", 301))

@Mukhammadamin2002
Copy link

You should change 301 to 302.

Copy link

ghost commented Jul 13, 2021

@donatj

You can skip the middle man and go:

http.HandleFunc("/", http.RedirectHandler("http://www.google.com", 301))

You should change http.HandleFunc to http.Handle

http.Handle("/", http.RedirectHandler("http://www.google.com", 302))

@markus-seidl
Copy link

For those suggesting 302 instead of 301:

301 Moved Permanently - https://en.wikipedia.org/wiki/HTTP_301
302 Found - https://en.wikipedia.org/wiki/HTTP_302

Depends on use case.

@donatj
Copy link

donatj commented Jul 10, 2022

Adding on to what @markus-seidl said, it might be nice to make the http code a parameter

@codenoid
Copy link

@markus-seidl we know, but the title are "Http Redirect in Golang" not "Http Permanent Redirect in Golang"

@keifgwinn
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment