Skip to content

Instantly share code, notes, and snippets.

@crast
Created August 3, 2016 21:13
Show Gist options
  • Save crast/4a1aaac95e14fbae554999e321c5ea01 to your computer and use it in GitHub Desktop.
Save crast/4a1aaac95e14fbae554999e321c5ea01 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"log"
"net/http"
)
/**
* This is a production-ready, horizontally shardable, super fast HTTPS-redirector.
*
* It takes the URL and redirects you to HTTPS where you would run your real service.
* This can work on a single port for any number of hosts so long as they aren't old browsers.
*/
func main() {
log.Fatal(http.ListenAndServe(":80", http.HandlerFunc(handler)))
}
func handler(w http.ResponseWriter, req *http.Request) {
host := req.Header.Get("Host")
if host == "" {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "Sorry, you did not send a Host header. Either you're a browser before 1996 or you're testing me with telnet. add https yourself.")
return
}
target := "https://" + host + req.RequestURI
w.Header.Set("Location", target)
w.WriteHeader(http.StatusMovedPermanently)
fmt.Fprintf(w, "Moved to %s", target)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment