17

[Golang] Get Domain Name from URL

 2 years ago
source link: http://siongui.github.io/2018/01/31/go-get-domain-name-from-url/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

[Golang] Get Domain Name from URL

January 31, 2018

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:

Run Code on Go Playground

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:

[2]Find DNS records of a domain using Golang : golang


Author: Siong-Ui Te Category: Go

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK