GO URL解析

Go对URL解析具有良好的支持。 URL包含方案, 身份验证信息, 主机, 端口, 路径, 查询参数和查询片段。我们可以解析URL并推断出要传入服务器的参数是什么, 然后相应地处理请求。
net / url软件包具有必需的功能, 例如Scheme, User, Host, Path, RawQuery等。
Go URL解析示例1

package mainimport "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}

【GO URL解析】输出:
mysqladmin:passwordadminpasswordserverhost.com:8081serverhost.com8081/server/page1Xkey=value& key2=value2map[key:[value] key2:[value2]]value2

Go URL解析示例2
package mainimport ( "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
GO URL解析

文章图片

    推荐阅读