在Go(Golang)中从一个URL中获取完整的主机名和端口的方法

556 阅读1分钟

概述

golang的net/url包包含一个Parse函数,可以用来解析给定的URL并返回URL结构的实例。 一旦给定的URL被正确解析,那么它将返回URI对象。然后我们就可以从URI中获取以下信息:

  • 方案

  • 用户信息

  • 主机名

  • 端口

  • 路径名称

  • 查询参数

  • 片段

一旦我们有了所有的部分,我们就可以把它们串联起来,得到完整的主机名和端口。我们将解析下面的URL

https://test:abcd123@golangbyexample.com:8000/tutorials/intro?type=advance&compact=false#history

然后,完整的主机名和端口将是

https://golangbyexample.com:8000

程序

下面是同样的程序。

package main

import (
	"fmt"
	"log"
	"net/url"
)

func main() {
	input_url := "https://test:abcd123@golangbyexample.com:8000/tutorials/intro?type=advance&compact=false#history"
	u, err := url.Parse(input_url)
	if err != nil {
		log.Fatal(err)
	}

	fullHostname := u.Scheme + "://" + u.Host

	fmt.Println(fullHostname)
}

输出

https://golangbyexample.com:8000:8000