Skip to content

Instantly share code, notes, and snippets.

@brydavis
Forked from d-schmidt/redirectExample.go
Created October 10, 2018 17:32
Show Gist options
  • Save brydavis/2dc29fb554b09737d20bd803b01a049a to your computer and use it in GitHub Desktop.
Save brydavis/2dc29fb554b09737d20bd803b01a049a to your computer and use it in GitHub Desktop.
How to redirect HTTP to HTTPS with a golang webserver.
package main
import (
"net/http"
"log"
)
func redirect(w http.ResponseWriter, req *http.Request) {
// remove/add not default ports from req.Host
target := "https://" + req.Host + req.URL.Path
if len(req.URL.RawQuery) > 0 {
target += "?" + req.URL.RawQuery
}
log.Printf("redirect to: %s", target)
http.Redirect(w, req, target,
// see @andreiavrammsd comment: often 307 > 301
http.StatusTemporaryRedirect)
}
func index(w http.ResponseWriter, req *http.Request) {
// all calls to unknown url paths should return 404
if req.URL.Path != "/" {
log.Printf("404: %s", req.URL.String())
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)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment