Go URL解析

Go语言对URL解析有很好的支持。URL包含协议方案、认证信息、主机、端口、路径、查询参数和查询片段。我们可以解析URL并推断出哪些参数正在发送到服务器,然后根据请求进行处理。

net/url包提供了一些必要的函数,如SchemeUserHostPathRawQuery等。

Go URL解析示例 1

goCopy code
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的协议方案
    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)      //将查询参数解析为映射
    p(m)        //打印参数映射
    p(m["key2"][0])     //打印特定键的值
}  

输出:

makefileCopy code
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

goCopy code
package main  
  
import (  
    "io"  
    "net/http"  
)  
  
  
func main() {  
    http.HandleFunc("/company", func(res http.ResponseWriter, req *http.Request) {  
        displayParameter(res, req)  
    })  
    println("在浏览器中输入URL: 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"))  
}  

输出:

在浏览器中输入URL: http://localhost:8080/company?name=Tom&age=27

go-url-passing1.png

标签: Golang, Golang下载, Golang教程, Golang技术, Golang学习, Golang学习教程, Golang语言, Golang开发, Golang入门教程, Golang进阶教程, Golang高级教程, Golang面试题, Golang笔试题, Golang编程思想