From d81b7a679aeb780c2f5c4b8cf80b3e1b444ded24 Mon Sep 17 00:00:00 2001 From: Kenta Iwasaki Date: Tue, 16 Jun 2020 04:04:29 +0900 Subject: [PATCH] cmd/flatend: add support for http -> https redirect --- cmd/flatend/http.go | 9 +++++++++ cmd/flatend/main.go | 39 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+) diff --git a/cmd/flatend/http.go b/cmd/flatend/http.go index 4905384..d7dc38d 100644 --- a/cmd/flatend/http.go +++ b/cmd/flatend/http.go @@ -1,6 +1,7 @@ package main import ( + "net" "net/http" "time" ) @@ -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 +} diff --git a/cmd/flatend/main.go b/cmd/flatend/main.go index a530398..4bcfbe6 100644 --- a/cmd/flatend/main.go +++ b/cmd/flatend/main.go @@ -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) @@ -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 {