在Go(Golang)中解析一个URL并提取所有的部分

4,685 阅读1分钟

概述

golang的net/url包包含一个Parse函数,可以用来解析一个给定的并返回URL结构的URL实例。

golang.org/pkg/net/url…

一旦给定的URL被正确解析,那么它将返回URI对象。然后我们就可以从URI中获取以下信息

  • 方案

  • 用户信息

  • 主机名

  • 端口

  • 路径名称

  • 查询参数

  • 片段

让我们看看同样的一个工作程序。

我们将解析下面的URL

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

然后

  • 方案是HTTPS

  • 用户信息 - 用户名是test,密码是abcd123。用户名和密码用冒号分开。

  • 主机名是www.golangbyexample.com

  • 端口是8000

  • 路径是tutorials/intro

  • 查询参数是type=advancecompact=false。它们之间用安培尔分隔

  • 片段是history。它将直接进入该页中的历史部分。历史是一个标识符,指的是该页中的该部分。

程序

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)
	}

	fmt.Println(u.Scheme)
	fmt.Println(u.User)
	fmt.Println(u.Hostname())
	fmt.Println(u.Port())
	fmt.Println(u.Path)
	fmt.Println(u.RawQuery)
	fmt.Println(u.Fragment)
	fmt.Println(u.String())
}

输出

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

从输出中可以看出,它正确地转储了所有的信息

The postParse a URL and extract all the parts in Go (Golang)appeared first onWelcome To Golang By Example.