Fix redirect to https with default http port

Fixes #528
This commit is contained in:
Jannis Mattheis 2022-12-03 11:28:12 +01:00
parent fe8a80d82f
commit 615aa5ce1c
2 changed files with 41 additions and 1 deletions

View File

@ -8,6 +8,7 @@ import (
"net"
"net/http"
"strconv"
"strings"
"time"
"github.com/gotify/server/v2/config"
@ -75,7 +76,11 @@ func redirectToHTTPS(port string) http.HandlerFunc {
func changePort(hostPort, port string) string {
host, _, err := net.SplitHostPort(hostPort)
if err != nil {
// There is no exported error.
if !strings.Contains(err.Error(), "missing port") {
return hostPort
}
host = hostPort
}
return net.JoinHostPort(host, port)
}

35
runner/runner_test.go Normal file
View File

@ -0,0 +1,35 @@
package runner
import (
"fmt"
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
)
func TestRedirect(t *testing.T) {
cases := []struct {
Request string
TLS int
Expect string
}{
{Request: "http://gotify.net/meow", TLS: 443, Expect: "https://gotify.net:443/meow"},
{Request: "http://gotify.net:8080/meow", TLS: 443, Expect: "https://gotify.net:443/meow"},
{Request: "http://gotify.net:8080/meow", TLS: 8443, Expect: "https://gotify.net:8443/meow"},
}
for _, testCase := range cases {
name := fmt.Sprintf("%s -- %d -> %s", testCase.Request, testCase.TLS, testCase.Expect)
t.Run(name, func(t *testing.T) {
req := httptest.NewRequest("GET", testCase.Request, nil)
rec := httptest.NewRecorder()
redirectToHTTPS(fmt.Sprint(testCase.TLS)).ServeHTTP(rec, req)
assert.Equal(t, http.StatusFound, rec.Result().StatusCode)
assert.Equal(t, testCase.Expect, rec.Header().Get("location"))
})
}
}