From bed0336608ca139cd5617be1949ae05aa6f6dc0e Mon Sep 17 00:00:00 2001 From: Josh Michielsen Date: Thu, 17 Oct 2019 22:04:24 +0100 Subject: [PATCH] Add SSL check and test no redirect when HTTPS Signed-off-by: Josh Michielsen --- http.go | 2 +- http_test.go | 21 +++++++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/http.go b/http.go index 0c84fb4b..9ef0499c 100644 --- a/http.go +++ b/http.go @@ -155,7 +155,7 @@ func (ln tcpKeepAliveListener) Accept() (c net.Conn, err error) { func redirectToHTTPS(opts *Options, h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if opts.ForceHTTPS { + if opts.ForceHTTPS && r.TLS == nil { http.Redirect(w, r, opts.HTTPSAddress, http.StatusPermanentRedirect) } diff --git a/http_test.go b/http_test.go index bfb9bb24..400213a0 100644 --- a/http_test.go +++ b/http_test.go @@ -135,3 +135,24 @@ func TestRedirectToHTTPSFalse(t *testing.T) { assert.Equal(t, http.StatusOK, rw.Code, "status code should be %d, got: %d", http.StatusOK, rw.Code) } + +func TestRedirectNotWhenHTTPS(t *testing.T) { + opts := NewOptions() + opts.ForceHTTPS = true + handler := func(w http.ResponseWriter, req *http.Request) { + w.Write([]byte("test")) + } + + h := redirectToHTTPS(opts, http.HandlerFunc(handler)) + s := httptest.NewTLSServer(h) + defer s.Close() + + opts.HTTPSAddress = s.URL + client := s.Client() + res, err := client.Get(s.URL) + if err != nil { + t.Fatalf("request to test server failed with error: %v", err) + } + + assert.Equal(t, http.StatusOK, res.StatusCode, "status code should be %d, got: %d", http.StatusOK, res.StatusCode) +}