Go对URL解析具有良好的支持。 URL包含方案,身份验证信息,主机,端口,路径,查询参数和查询片段。我们可以解析URL并推断出要传入服务器的参数是什么,然后相应地处理请求。
net/url软件包具有必需的功能,例如Scheme,User,Host,Path,RawQuery等。
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) //打印 URL 的 Schema p(u.User) // 打印解析的用户和密码 p(u.User.Username()) //打印用户名 pass, _ := u.User.Password() p(pass) //打印用户密码 p(u.Host) //打印主机和端口 host, port, _ := net.SplitHostPort(u.Host) //拆分主机名和端口 p(host) //打印主机 p(port) //打印端口 p(u.Path) //打印路径 p(u.Fragment) //打印片段路径值 p(u.RawQuery) //打印提供的查询参数名称和值 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
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")) }
输出:
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)