diff --git a/proxy/url.go b/proxy/url.go new file mode 100644 index 00000000..0f6bcf31 --- /dev/null +++ b/proxy/url.go @@ -0,0 +1,45 @@ +package proxy + +import ( + "errors" + "net/url" + "strings" +) + +// URL is the universal representation of the proxy configuration. +type URL url.URL + +func (u *URL) Protocol() string { + return u.Scheme +} + +func (u *URL) Address() string { + return u.Host +} + +func (u *URL) String() string { + return (&url.URL{ + Scheme: u.Scheme, + Host: u.Host, + Path: strings.TrimRight(u.Path, "/"), + }).String() +} + +func ParseURL(rawURL string) (*URL, error) { + proxyURL, err := url.Parse(rawURL) + if err != nil { + return nil, err + } + if proxyURL.Scheme == "" { + return nil, errors.New("proxy: protocol not specified") + } + return (*URL)(proxyURL), nil +} + +func MustParseURL(rawURL string) *URL { + u, err := ParseURL(rawURL) + if err != nil { + panic(err) + } + return u +} diff --git a/proxy/url_test.go b/proxy/url_test.go new file mode 100644 index 00000000..16ee472f --- /dev/null +++ b/proxy/url_test.go @@ -0,0 +1,31 @@ +package proxy + +import ( + "testing" + + "github.com/stretchr/testify/suite" +) + +type URLTestSuite struct { + suite.Suite +} + +func (s *URLTestSuite) TestAddress() { + tests := []struct { + u *URL + expected string + }{ + { + MustParseURL("http://example.com/"), + "http://example.com", + }, + } + for _, tt := range tests { + s.Assert().Equal(tt.expected, tt.u.String()) + } + +} + +func TestURLTestSuite(t *testing.T) { + suite.Run(t, new(URLTestSuite)) +}