[Golang] Get Domain Name from URL
Get domain name from URL via Go net/url package in standard library.
Question:
Assume the URL is
https://siongui.github.io/pali-chanting/zh/archives.html
I want to get the domain name github.io from the URL. How to do it in Go?
Answer:
package main
import (
"fmt"
"log"
"net/url"
"strings"
)
func main() {
u, err := url.Parse("https://siongui.github.io/pali-chanting/zh/archives.html")
if err != nil {
log.Fatal(err)
}
parts := strings.Split(u.Hostname(), ".")
domain := parts[len(parts)-2] + "." + parts[len(parts)-1]
fmt.Println(domain)
}
Tested on: Go Playground
References:
[1] |
[2] | Find DNS records of a domain using Golang : golang |