2. DNS

A "domain name"arrow-up-right or "hostname"arrow-up-right is just one portion of a URL. We'll get to the other parts of a URL later.

For example, the URL https://homestarrunner.com/toons has a hostname of homestarrunner.com. The https:// and /toons portions aren't part of the domain name -> IP address mapping that we've been talking about.

The net/url Package

The net/url package is part of Go's standard library. You can instantiate a URL structarrow-up-right using url.Parse:

parsedURL, err := url.Parse("https://homestarrunner.com/toons")
if err != nil {
	fmt.Println("error parsing url:", err)
	return
}

And then you can extract just the hostnamearrow-up-right:

parsedURL.Hostname()
// homestarrunner.com

Assignment

Complete the getDomainNameFromURL function. Given a full URL, it should return the domain (or host) name. Simply return any potential errors.

Solution

main.go
package main

import (
	"net/url"
)

func getDomainNameFromURL(rawURL string) (string, error) {
	parsed, err := url.Parse(rawURL)
	if err != nil {
		return "", err
	}

	return parsed.Hostname(), nil
}