Skip to content

Commit b901486

Browse files
committed
Add automatic redirect to https if both http and https are configured
1 parent 8f14813 commit b901486

File tree

1 file changed

+35
-7
lines changed

1 file changed

+35
-7
lines changed

cmd/tunneld/tunneld.go

Lines changed: 35 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import (
99
"crypto/x509"
1010
"fmt"
1111
"io/ioutil"
12+
"net"
1213
"net/http"
1314
"os"
1415
"strings"
@@ -68,13 +69,40 @@ func main() {
6869
// start HTTP
6970
if opts.httpAddr != "" {
7071
go func() {
71-
logger.Log(
72-
"level", 1,
73-
"action", "start http",
74-
"addr", opts.httpAddr,
75-
)
76-
77-
fatal("failed to start HTTP: %s", http.ListenAndServe(opts.httpAddr, server))
72+
if opts.httpsAddr != "" {
73+
logger.Log(
74+
"level", 1,
75+
"action", "start http redirect",
76+
"addr", opts.httpAddr,
77+
)
78+
79+
_, tlsPort, err := net.SplitHostPort(opts.httpsAddr)
80+
if err != nil {
81+
fatal("failed to get https port: %s", err)
82+
}
83+
fatal("failed to start HTTP: %s",
84+
http.ListenAndServe(opts.httpAddr, http.HandlerFunc(
85+
func(w http.ResponseWriter, r *http.Request) {
86+
host, _, err := net.SplitHostPort(r.Host)
87+
if err != nil {
88+
host = r.Host
89+
}
90+
u := r.URL
91+
u.Host = net.JoinHostPort(host, tlsPort)
92+
u.Scheme = "https"
93+
http.Redirect(w, r, u.String(), http.StatusMovedPermanently)
94+
},
95+
)),
96+
)
97+
} else {
98+
logger.Log(
99+
"level", 1,
100+
"action", "start http",
101+
"addr", opts.httpAddr,
102+
)
103+
104+
fatal("failed to start HTTP: %s", http.ListenAndServe(opts.httpAddr, server))
105+
}
78106
}()
79107
}
80108

0 commit comments

Comments
 (0)