Skip to content

Instantly share code, notes, and snippets.

@jaymecd
Forked from d-schmidt/redirectExample.go
Created October 11, 2016 21:20
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jaymecd/a8474e9d646e3842dc0e1f22db8b5e8e to your computer and use it in GitHub Desktop.
Save jaymecd/a8474e9d646e3842dc0e1f22db8b5e8e to your computer and use it in GitHub Desktop.
How to redirect HTTP to HTTPS with a golang webserver.
package main
import (
"net/http"
)
func redirect(w http.ResponseWriter, req *http.Request) {
http.Redirect(w, req,
"https://" + req.Host + req.URL.String(),
http.StatusMovedPermanently)
}
func index(w http.ResponseWriter, req *http.Request) {
// all calls to unknown url paths should return 404
if req.URL.Path != "/" {
http.NotFound(w, req)
return
}
http.ServeFile(w, req, "index.html")
}
func main() {
// redirect every http request to https
go http.ListenAndServe(":80", http.HandlerFunc(redirect))
// serve index (and anything else) as https
mux := http.NewServeMux()
mux.HandleFunc("/", index)
http.ListenAndServeTLS(":443", "cert.pem", "key.pem", mux)
}
@sumohammed
Copy link

hello ,
i just tried your approach to redirecting and its not working. Whenever i run it the goruntine with the listenAndServe never gets called for some reason

@aerialcombat
Copy link

Worked perfectly!

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