Cookies management by TermsFeed Cookie Consent
Russia has invaded Ukraine and already killed tens of thousands of civilians, with many more raped or tortured. It's a genocide. We need your help. Let's fight back against the Russian regime.
Help Ukraine! Fight the Russian regime!

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

shorts url

Please consider supporting us by disabling your ad blocker

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

🧊 Cube root in Go

shorts numbers math

🟦 Square root in Go

shorts numbers math

🍰 The maximum and minimum value of the int types in Go

shorts numbers math