diff --git a/internal/httputil/server.go b/internal/httputil/server.go index c7d76bdda..393a076b9 100644 --- a/internal/httputil/server.go +++ b/internal/httputil/server.go @@ -4,10 +4,10 @@ import ( "context" "crypto/tls" "errors" - "fmt" stdlog "log" "net" "net/http" + "net/url" "os" "os/signal" "sync" @@ -69,9 +69,13 @@ func NewServer(opt *ServerOptions, h http.Handler, wg *sync.WaitGroup) (*http.Se // RedirectHandler takes an incoming request and redirects to its HTTPS counterpart func RedirectHandler() http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + newURL := new(url.URL) + *newURL = *r.URL + newURL.Scheme = "https" + newURL.Host = urlutil.StripPort(r.Host) + w.Header().Set("Connection", "close") - url := fmt.Sprintf("https://%s", urlutil.StripPort(r.Host)) - http.Redirect(w, r, url, http.StatusMovedPermanently) + http.Redirect(w, r, newURL.String(), http.StatusMovedPermanently) }) } diff --git a/internal/httputil/server_test.go b/internal/httputil/server_test.go index d8d8830df..8321cf7db 100644 --- a/internal/httputil/server_test.go +++ b/internal/httputil/server_test.go @@ -130,16 +130,17 @@ func waitSig(t *testing.T, c <-chan os.Signal, sig os.Signal) { func TestRedirectHandler(t *testing.T) { tests := []struct { - name string + url string wantStatus int wantBody string }{ {"http://example", http.StatusMovedPermanently, "Moved Permanently.\n\n"}, {"http://example:8080", http.StatusMovedPermanently, "Moved Permanently.\n\n"}, + {"http://example:8080/some/path?x=y", http.StatusMovedPermanently, "Moved Permanently.\n\n"}, } for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - req := httptest.NewRequest(http.MethodGet, "http://example/", nil) + t.Run(tt.url, func(t *testing.T) { + req := httptest.NewRequest(http.MethodGet, tt.url, nil) rr := httptest.NewRecorder() RedirectHandler().ServeHTTP(rr, req) if diff := cmp.Diff(tt.wantStatus, rr.Code); diff != "" {