Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the subdomain

Tags:

go

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!

like image 459
user_78361084 Avatar asked Apr 12 '26 21:04

user_78361084


1 Answers

Use PublicSuffix:

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