user_78361084
user_78361084

Reputation: 3928

Getting the subdomain

I am parsing a few urls and need to extract the subdomain from the Host. The simplest way is to get the Host using "url.Parse()" and then split the Host on "." and if there are 3 parts then the subdomain is the first part. This will work for U.S. TLD's but is there a better way to extract the subdomain that will work across all TLD's? For instance:

url = "www.google.com" // "www"
url2 = "google.com" // ""
url3 = "www.google.co.uk"  // "www.google"
url4 = "google.co.uk"  // "google"
parts, err := url.Parse(url)

thx!

Upvotes: 3

Views: 642

Answers (1)

user4122236
user4122236

Reputation:

Use PublicSuffix:

suffix, _ := publicsuffix.PublicSuffix(host)
sub := host[:len(host) - len(suffix) - 1]

Upvotes: 5

Related Questions