To get a hostname or domain from a URL in Go, first, use the url.Parse()
function, which parses the URL given as input, and then use the url.Hostname()
method, which returns the hostname. If you do not want the www.
prefix in your domain name, remove it with the strings.TrimPrefix()
function.
package main
import (
"fmt"
"log"
"net/url"
"strings"
)
func main() {
input := "https://www.gosamples.dev/abc/def"
url, err := url.Parse(input)
if err != nil {
log.Fatal(err)
}
hostname := strings.TrimPrefix(url.Hostname(), "www.")
fmt.Println(hostname)
}
Output:
gosamples.dev