Skip to content

Commit

Permalink
cmd/flatend: add support for http -> https redirect
Browse files Browse the repository at this point in the history
  • Loading branch information
lithdew committed Jun 15, 2020
1 parent c296bc1 commit d81b7a6
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
9 changes: 9 additions & 0 deletions cmd/flatend/http.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package main

import (
"net"
"net/http"
"time"
)
Expand Down Expand Up @@ -40,3 +41,11 @@ func NoCache(h http.Handler) http.Handler {

return http.HandlerFunc(fn)
}

func hostOnly(hostPort string) string {
host, _, err := net.SplitHostPort(hostPort)
if err != nil {
return hostPort // OK; probably had no port to begin with
}
return host
}
39 changes: 39 additions & 0 deletions cmd/flatend/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -130,8 +130,37 @@ func main() {
acme := certmagic.NewACMEManager(magic, certmagic.DefaultACME)
srv.Handler = acme.HTTPChallengeHandler(srv.Handler)

redirect := &http.Server{
Handler: acme.HTTPChallengeHandler(
http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
toURL := "https://"

requestHost := hostOnly(r.Host)

toURL += requestHost
toURL += r.URL.RequestURI()

w.Header().Set("Connection", "close")

http.Redirect(w, r, toURL, http.StatusMovedPermanently)
},
),
),
ReadTimeout: cfg.Timeout.Read.Duration,
ReadHeaderTimeout: cfg.Timeout.ReadHeader.Duration,
IdleTimeout: cfg.Timeout.Idle.Duration,
WriteTimeout: cfg.Timeout.Write.Duration,
MaxHeaderBytes: cfg.Max.HeaderSize,
}

defer func() {
check(redirect.Close())
}()

for _, addr := range addrs {
addr := addr

go func() {
ln, err := tls.Listen("tcp", net.JoinHostPort(addr, "443"), magic.TLSConfig())
check(err)
Expand All @@ -141,6 +170,16 @@ func main() {
check(err)
}
}()

go func() {
ln, err := net.Listen("tcp", net.JoinHostPort(addr, "80"))
check(err)

err = redirect.Serve(ln)
if !errors.Is(err, http.ErrServerClosed) {
check(err)
}
}()
}
} else {
for _, addr := range addrs {
Expand Down

0 comments on commit d81b7a6

Please sign in to comment.