Skip to content

Commit

Permalink
refactor: use url.Parse instead of regex
Browse files Browse the repository at this point in the history
  • Loading branch information
JuArce committed Oct 25, 2024
1 parent 8c41436 commit 207a83d
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 30 deletions.
20 changes: 6 additions & 14 deletions operator/pkg/utils.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
package operator

import (
"fmt"
"github.com/yetanotherco/aligned_layer/common"
"math/big"
"regexp"
"net/url"
)

func IsVerifierDisabled(disabledVerifiersBitmap *big.Int, verifierId common.ProvingSystemId) bool {
Expand All @@ -17,18 +16,11 @@ func IsVerifierDisabled(disabledVerifiersBitmap *big.Int, verifierId common.Prov
}

func BaseUrlOnly(input string) (string, error) {
// Define a regex pattern to match the URL format
// The pattern captures the scheme, host, and path
pattern := `^(?P<scheme>[^:]+)://(?P<host>[^/]+)(?P<path>/.*)?$`
re := regexp.MustCompile(pattern)

matches := re.FindStringSubmatch(input)

if matches == nil {
return "", fmt.Errorf("invalid URL: %s", input)
// https://gobyexample.com/url-parsing
u, err := url.Parse(input)
if err != nil {
return "", err
}

host := matches[2]

return host, nil
return u.Host, nil
}
23 changes: 7 additions & 16 deletions operator/pkg/utils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,13 @@ func TestBaseUrlOnlyHappyPath(t *testing.T) {
{"https://a.b.c.d/1234", "a.b.c.d"},
{"https://a.b.c.d/1234/5678", "a.b.c.d"},
{"https://a.b.c.d.e/1234/", "a.b.c.d.e"},
{"https://a.b.c.d?e=1234", "a.b.c.d"},
{"https://a.b.c.d/rpc?e=1234", "a.b.c.d"},
{"wss://a.b.c.d/1234", "a.b.c.d"},
{"wss://a.b.c.d/1234/5678", "a.b.c.d"},
{"wss://a.b.c.d.e/1234/", "a.b.c.d.e"},
{"wss://a.b.c.d?e=1234", "a.b.c.d"},
{"wss://a.b.c.d/rpc?e=1234", "a.b.c.d"},
}

for _, pair := range urls {
Expand All @@ -81,19 +88,3 @@ func TestBaseUrlOnlyHappyPath(t *testing.T) {
}
}
}

func TestBaseUrlOnlyFailureCases(t *testing.T) {

urls := [...]string{
"localhost:8545/asdfoij2a7831has89%342jddav98j2748",
"this-is-all-wrong",
}

for _, url := range urls {
baseUrl, err := BaseUrlOnly(url)

if err == nil {
t.Errorf("An error was expected, but received %s", baseUrl)
}
}
}

0 comments on commit 207a83d

Please sign in to comment.