📜  Go语言 URL解析

📅  最后修改于: 2021-01-02 09:37:53             🧑  作者: Mango

转到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