Go URL解析
Go URL 解析
Go 对 url 解析有很好的支持。 URL 包含方案、身份验证信息、主机、端口、路径、查询参数和查询片段。我们可以解析 URL 并推断出传入服务器的参数是什么,然后相应地处理请求。
net/url 包具有所需的功能,如 Scheme、User、Host、Path、RawQuery 等。
Go URL 解析示例 1
package main
import "fmt"
import "net"
import "net/url"
func main() {
p := fmt.Println
s := "Mysql://admin:password@serverhost.com:8081/server/page1?key=value&key2=value2#X"
u, err := url.Parse(s)
if err != nil {
panic(err)
}
p(u.Scheme) //prints Schema of the URL
p(u.User) // prints the parsed user and password
p(u.User.Username()) //prints user's name
pass, _ := u.User.Password()
p(pass) //prints user password
p(u.Host) //prints host and port
host, port, _ := net.SplitHostPort(u.Host) //splits host name and port
p(host) //prints host
p(port) //prints port
p(u.Path) //prints the path
p(u.Fragment) //prints fragment path value
p(u.RawQuery) //prints query param name and value as provided
m, _ := url.ParseQuery(u.RawQuery) //parse query param into map
p(m) //prints param map
p(m["key2"][0]) //prints specific key value
}
输出:
mysql
admin:password
admin
password
serverhost.com:8081
serverhost.com
8081
/server/page1
X
key=value&key2=value2
map[key:[value] key2:[value2]]
value2
Go URL 解析示例 2
package main
import (
"io"
"net/http"
)
func main() {
http.HandleFunc("/company", func(res http.ResponseWriter, req *http.Request) {
displayParameter(res, req)
})
println("Enter the url in browser: http://localhost:8080/company?name=Tom&age=27")
http.ListenAndServe(":8080", nil)
}
func displayParameter(res http.ResponseWriter, req *http.Request) {
io.WriteString(res, "name: "+req.FormValue("name"))
io.WriteString(res, "\nage: "+req.FormValue("age"))
}
输出:
在浏览器中输入网址: http://localhost:8080/company ?name=Tom&age=27