Skip to main content
  1. Tutorials/

👀 Get a hostname (domain) from a URL in Go

·1 min

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