Cookies management by TermsFeed Cookie Consent

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

shorts url

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

Thank you for being on our site 😊. If you like our tutorials and examples, please consider supporting us with a cup of coffee and we'll turn it into more great Go examples.

Have a great day!

Buy Me A Coffee

🔗 Join URL path elements in Go

shorts net url path

⏰ Handle HTTP timeout error in Go

shorts http

🐾 How to compare strings in Go

shorts introduction strings