From 78885cc66a0bb5db6272e499282ab46033f3bb71 Mon Sep 17 00:00:00 2001 From: stephen mcquay Date: Mon, 1 Feb 2016 20:54:46 -0800 Subject: [PATCH] redirect non-tls port --- main.go | 52 +++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 49 insertions(+), 3 deletions(-) diff --git a/main.go b/main.go index 148d7e7..eccfb88 100644 --- a/main.go +++ b/main.go @@ -2,9 +2,11 @@ package main import ( "fmt" + "net" "net/http" "os" "strconv" + "strings" ) const usage = "servetls " @@ -18,7 +20,17 @@ func main() { http.HandleFunc("/", handler) - port := 8443 + tlsPort := 8443 + if os.Getenv("TLS_PORT") != "" { + p, err := strconv.Atoi(os.Getenv("TLS_PORT")) + if err != nil { + fmt.Fprintf(os.Stderr, "could not parse TLS_PORT variable: %s\n", os.Getenv("TLS_PORT")) + os.Exit(1) + } + tlsPort = p + } + + port := 8000 if os.Getenv("PORT") != "" { p, err := strconv.Atoi(os.Getenv("PORT")) if err != nil { @@ -27,8 +39,22 @@ func main() { } port = p } - addr := fmt.Sprintf(":%d", port) - fmt.Printf("serving on %s", addr) + + go func() { + b := &bouncer{tlsPort} + + sm := http.NewServeMux() + sm.Handle("/", b) + + addr := fmt.Sprintf(":%d", port) + if err := http.ListenAndServe(addr, sm); err != nil { + panic(err) + } + }() + + fmt.Printf("redirecting on :%d\n", port) + fmt.Printf("serving on :%d\n", tlsPort) + addr := fmt.Sprintf(":%d", tlsPort) err := http.ListenAndServeTLS(addr, cert, key, nil) if err != nil { fmt.Fprintf(os.Stderr, "%v\n", err) @@ -39,3 +65,23 @@ func main() { func handler(w http.ResponseWriter, req *http.Request) { fmt.Fprintf(w, "if you see this without complaints things are likely set up correctly\n") } + +type bouncer struct { + port int +} + +func (b *bouncer) ServeHTTP(w http.ResponseWriter, req *http.Request) { + var host string + var err error + if strings.Contains(req.Host, ":") { + host, _, err = net.SplitHostPort(req.Host) + if err != nil { + http.Error(w, "couldn't parse hostname from requeest", http.StatusBadRequest) + return + } + } else { + host = req.Host + } + url := fmt.Sprintf("https://%s:%d/", host, b.port) + http.Redirect(w, req, url, http.StatusMovedPermanently) +}