diff --git a/urls.go b/urls.go index d3463ab..75f40b3 100644 --- a/urls.go +++ b/urls.go @@ -24,3 +24,14 @@ func CreateURL(origin, path string, params map[string]string) *url.URL { u.RawQuery = query.Encode() return u } + +// GetDomain extracts the domain name from a given url s. +// +// If s is not a valid url, the empty string is returned. +func GetDomain(s string) string { + u, uerr := url.Parse(s) + if uerr != nil { + return "" + } + return u.Host +} diff --git a/urls_test.go b/urls_test.go index a6f0116..c6db20e 100644 --- a/urls_test.go +++ b/urls_test.go @@ -18,3 +18,11 @@ func TestCreateURL(t *testing.T) { u := CreateURL(orig, "/hello", params) must.Eq(t, "http://example.org:8000/hello?key=abc123&offset=3", u.String()) } + +func TestGetDomain(t *testing.T) { + t.Parallel() + + orig := "http://stage.example.org/foo/bar" + result := GetDomain(orig) + must.Eq(t, "stage.example.org", result) +}