Skip to content

Commit

Permalink
chore: use better URI parsing
Browse files Browse the repository at this point in the history
  • Loading branch information
dkoshkin committed Nov 3, 2022
1 parent 4a208f3 commit 1bc5765
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 20 deletions.
39 changes: 20 additions & 19 deletions cmd/mindthegap/flags/custom_flags.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,13 @@
package flags

import (
"strings"
"fmt"
"net/url"
"path"
)

const (
httpScheme = "http"
httpsScheme = "https"

httpSchemePrefix = "http://"
httpsSchemePrefix = "https://"
httpScheme = "http"
)

type RegistryURI struct {
Expand All @@ -25,25 +23,28 @@ func (v RegistryURI) String() string {
return v.raw
}

func (v *RegistryURI) Set(value string) error {
func (v *RegistryURI) Set(value string) (err error) {
v.raw = value
v.scheme, v.address = parsePossibleURI(value)
v.scheme, v.address, err = parsePossibleURI(value)

return nil
return
}

func parsePossibleURI(value string) (string, string) {
scheme := ""
address := value
if strings.HasPrefix(value, httpSchemePrefix) {
scheme = httpScheme
address = strings.TrimPrefix(value, httpSchemePrefix)
} else if strings.HasPrefix(value, httpsSchemePrefix) {
scheme = httpsScheme
address = strings.TrimPrefix(value, httpsSchemePrefix)
func parsePossibleURI(raw string) (scheme string, address string, err error) {
u, err := url.ParseRequestURI(raw)
if err != nil || u.Host == "" {
// parse again with a scheme to make it a valid URI
u, err = url.ParseRequestURI("dummy://" + raw)
if err != nil {
return "", "", fmt.Errorf("could not parse raw url: %q, error: %w", raw, err)
}
} else {
// only set the scheme when set by the caller
scheme = u.Scheme
}

return scheme, address
address = path.Join(u.Host, u.Path)
return
}

func (v RegistryURI) Scheme() string {
Expand Down
2 changes: 1 addition & 1 deletion cmd/mindthegap/flags/custom_flags_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ func Test_parsePossibleURI(t *testing.T) {
tt := tests[ti]
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
scheme, address := parsePossibleURI(tt.in)
scheme, address, _ := parsePossibleURI(tt.in)
require.Equal(t, tt.expectedScheme, scheme)
require.Equal(t, tt.expectedAddress, address)
})
Expand Down

0 comments on commit 1bc5765

Please sign in to comment.