在 Golang 中解析 URL
package main import ( "fmt" "log" "net/url" ) func TestURL() { URL, err := url.Parse("http://bing.com/good%2bad") fmt.Println("Url before modification is", URL) if err != nil { log.Fatal("An error occurs while handling url", err) } fmt.Println("The URL path is", URL.Path) fmt.Println("The URL raw path is", URL.RawPath) fmt.Println("The URL is ", URL.String()) } func main() { TestURL() }
运行代码:
$ go run main.go Url before modification is http://bing.com/good%2bad The URL path is /good+ad The URL raw path is /good%2bad The URL is http://bing.com/good%2bad
处理相对路径
package main import ( "fmt" "log" "net/url" ) func ExampleURL() { URL, error := url.Parse("../../..//search?q=php") fmt.Println("Url before modification is", URL) if error != nil { log.Fatal("An error occurs while handling url", error) } baseURL, err := url.Parse("http://example.com/directory/") if err != nil { log.Fatal("An error occurs while handling url", err) } fmt.Println(baseURL.ResolveReference(URL)) } func main() { ExampleURL() }
$ go run main.go Url before modification is ../../..//search?q=php http://example.com/search?q=php
解析空格
package main import ( "fmt" "log" "net/url" ) func ExampleURL() { URL, error := url.Parse("http://example.com/Here path with space") if error != nil { log.Fatal("An error occurs while handling url", error) } fmt.Println("The Url is", URL) } func main() { ExampleURL() }
运行结果:
$ go run main.go The Url is http://example.com/Here%20path%20with%20space
判断绝对地址
package main import ( "fmt" "net/url" ) func main() { u := url.URL{Host: "example.com", Path: "foo"} fmt.Println("The Url is", u.IsAbs()) u.Scheme = "http" fmt.Println("The Url is", u.IsAbs()) }
$ go run main.go The Url is false The Url is true
解析端口
package main import ( "fmt" "log" "net/url" ) func ExampleURL() { URL1, error := url.Parse("https://example.org") fmt.Println("URL1 before modification is", URL1) if error != nil { log.Fatal("An error occurs while handling url", error) } URL2, err := url.Parse("https://example.org:8080") if err != nil { log.Fatal("An error occurs while handling url", URL2) } fmt.Println("URL2 before modification is", URL2) fmt.Println("URL2 Port number is", URL2.Port()) } func main() { ExampleURL() }
$ go run main.go URL1 before modification is https://example.org URL2 before modification is https://example.org:8080 URL2 Port number is 8080
总结
从本教程中,我们了解了 go url
包 的基本概念,并了解了 url
的概念语法。并逐渐展示了 url
的部分功能以及 url
的主要用途,希望读者可以在官方文档中学习其他方法。