Created
April 9, 2013 05:38
-
-
Save hSATAC/5343225 to your computer and use it in GitHub Desktop.
Http Redirect in Golang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} |
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))
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.
Adding on to what @markus-seidl said, it might be nice to make the http code a parameter
@markus-seidl we know, but the title are "Http Redirect in Golang" not "Http Permanent Redirect in Golang"
@donatj I did that over here https://github.com/keifgwinn/redirector
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You should change 301 to 302.