redirect non-tls port

This commit is contained in:
Stephen McQuay 2016-02-01 20:54:46 -08:00
parent 346b7ecd32
commit 78885cc66a
1 changed files with 49 additions and 3 deletions

52
main.go
View File

@ -2,9 +2,11 @@ package main
import ( import (
"fmt" "fmt"
"net"
"net/http" "net/http"
"os" "os"
"strconv" "strconv"
"strings"
) )
const usage = "servetls <cert file> <key file>" const usage = "servetls <cert file> <key file>"
@ -18,7 +20,17 @@ func main() {
http.HandleFunc("/", handler) 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") != "" { if os.Getenv("PORT") != "" {
p, err := strconv.Atoi(os.Getenv("PORT")) p, err := strconv.Atoi(os.Getenv("PORT"))
if err != nil { if err != nil {
@ -27,8 +39,22 @@ func main() {
} }
port = p 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) err := http.ListenAndServeTLS(addr, cert, key, nil)
if err != nil { if err != nil {
fmt.Fprintf(os.Stderr, "%v\n", err) fmt.Fprintf(os.Stderr, "%v\n", err)
@ -39,3 +65,23 @@ func main() {
func handler(w http.ResponseWriter, req *http.Request) { func handler(w http.ResponseWriter, req *http.Request) {
fmt.Fprintf(w, "if you see this without complaints things are likely set up correctly\n") 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)
}