url.Parse
URL结构
URL(Uniform Resource Locator)统一资源定位符,就是由一串简单的文本字符组成。一条符合规范的URL对应的是服务器的一个特定的资源(如HTML页面,一张图片等)。
URL结构:
Scheme://Login:password@Address:port/path/to/resource?query_string#fragment
-
Scheme
协议,如http,https,ftp等 -
Login:password@
身份验证 -
Address
服务器地址 -
Port
服务器端口 -
/path/to/resource
文件路径 -
?query_string
查询字符串 -
#fragment
片段ID,如http页面中内部的标签
Golang解析URL
url.Parse
package main
import (
"log"
"net/url"
)
func main() {
site := "http://xiaoming:123456@www.example.com:8080/resource/level/next?file=got.rar×tamp=123432#temp"
r, err := url.Parse(site)
if err != nil {
log.Fatalln("parse url [%v] failed!", site)
}
log.Printf("parse url value is [%v]", r)
log.Printf("Schema is [%v]", r.Scheme)
log.Printf("Login is [%v]", r.User.Username())
if password, ok := r.User.Password(); ok {
log.Printf("Password is [%v]", password)
}
log.Printf("Address is [%v]", r.Hostname())
log.Printf("Port is [%v]", r.Port())
log.Printf("Resource is [%v]", r.Path)
log.Printf("Query is [%v]", r.Query())
log.Printf("Fragment is [%v]", r.Fragment)
}
输出结果如下所示
2021/12/31 00:21:36 parse url value is [http://xiaoming:123456@www.example.com:8080/resource/level/next?file=got.rar×tamp=123432#temp]
2021/12/31 00:21:36 Schema is [http]
2021/12/31 00:21:36 Login is [xiaoming]
2021/12/31 00:21:36 Password is [123456]
2021/12/31 00:21:36 Address is [www.example.com]
2021/12/31 00:21:36 Port is [8080]
2021/12/31 00:21:36 Resource is [/resource/level/next]
2021/12/31 00:21:36 Query is [map[file:[got.rar] timestamp:[123432]]]
2021/12/31 00:21:36 Fragment is [temp]
参考资料: