From 2cc60dce66ad68016503e4704d5f8a092350dedc Mon Sep 17 00:00:00 2001 From: boreq Date: Mon, 20 Nov 2023 15:35:45 +0100 Subject: [PATCH] Normalize relay addresses --- service/domain/relay_address.go | 3 ++ service/domain/relay_address_test.go | 53 ++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+) create mode 100644 service/domain/relay_address_test.go diff --git a/service/domain/relay_address.go b/service/domain/relay_address.go index 327e2d2..1fcdb79 100644 --- a/service/domain/relay_address.go +++ b/service/domain/relay_address.go @@ -11,6 +11,9 @@ type RelayAddress struct { } func NewRelayAddress(s string) (RelayAddress, error) { + s = strings.TrimSpace(s) + s = strings.TrimRight(s, "/") + if !strings.HasPrefix(s, "ws://") && !strings.HasPrefix(s, "wss://") { return RelayAddress{}, errors.New("invalid protocol") } diff --git a/service/domain/relay_address_test.go b/service/domain/relay_address_test.go new file mode 100644 index 0000000..c547ceb --- /dev/null +++ b/service/domain/relay_address_test.go @@ -0,0 +1,53 @@ +package domain + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func TestRelayAddress(t *testing.T) { + testCases := []struct { + Input string + Output string + }{ + { + Input: "wss://example.com", + Output: "wss://example.com", + }, + { + Input: "ws://example.com", + Output: "ws://example.com", + }, + + { + Input: " wss://example.com", + Output: "wss://example.com", + }, + { + Input: "wss://example.com ", + Output: "wss://example.com", + }, + { + Input: " wss://example.com ", + Output: "wss://example.com", + }, + + { + Input: "wss://example.com/", + Output: "wss://example.com", + }, + { + Input: "wss://example.com/ ", + Output: "wss://example.com", + }, + } + + for _, testCase := range testCases { + t.Run(testCase.Input, func(t *testing.T) { + result, err := NewRelayAddress(testCase.Input) + require.NoError(t, err) + require.Equal(t, testCase.Output, result.String()) + }) + } +}