net/http包中的http.request方法和参数梳理
本文测试的是GET请求方式
请求的URL为: localhost:8088/api/v1/getTest?start=1h-ago&end=30m-ago&m=sum:30m-sum:true:proc.stat.cpu{host=foo,type=idle}&ms=true 通过Postman以GET方式发送该请求。 控制台输出的各种参数和方法的值如下
1. 示例代码
func (mux *MyMux) parseGetParameter(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" { http.Error(w, "the method is not allowed", http.StatusMethodNotAllowed) } fmt.Println("r.URL.RawQuery: ", r.URL.RawQuery) fmt.Println("r.URL.Path: ", r.URL.Path) fmt.Println("r.URL.Host: ", r.URL.Host) fmt.Println("r.URL.Fragment: ", r.URL.Fragment) fmt.Println("r.URL.Opaque: ", r.URL.Opaque) fmt.Println("r.URL.RawPath: ", r.URL.RawPath) fmt.Println("r.URL.Scheme: ", r.URL.Scheme) fmt.Println() fmt.Println("r.URL.RequestURI(): ", r.URL.RequestURI()) fmt.Println("r.URL.Hostname(): ", r.URL.Hostname()) fmt.Println("r.URL.Port(): ", r.URL.Port()) fmt.Println("r.URL.String(): ", r.URL.String()) fmt.Println("r.URL.EscapedPath(): ", r.URL.EscapedPath()) fmt.Println() fmt.Println("r.Host: ", r.Host) fmt.Println("r.Method: ", r.Method) fmt.Println("r.UserAgent(): ", r.UserAgent()) fmt.Println("r.RequestURI: ", r.RequestURI) fmt.Println("r.RemoteAddr: ", r.RemoteAddr) fmt.Println("r.FormValue(start): ", r.FormValue("start")) fmt.Println("r.FormValue(end): ", r.FormValue("end")) fmt.Println("r.FormValue(m): ", r.FormValue("m")) fmt.Println("r.FormValue(ms): ", r.FormValue("ms")) fmt.Println() fmt.Println("r.URL.Query().Get(start): ", r.URL.Query().Get("start")) fmt.Println("r.URL.Query().Get(end):", r.URL.Query().Get("end")) fmt.Println("r.URL.Query().Get(m):", r.URL.Query().Get("m")) fmt.Println("r.r.URL.Query()", r.URL.Query()) fmt.Println("r.r.URL.Query()[“”"m"]", r.URL.Query()["m"]) fmt.Println("r.URL.Query().Get(ms):", r.URL.Query().Get("ms")) fmt.Println("r.Header.Get(Content-Type):", r.Header.Get("Content-Type"))
}
2. 示例结果
请注意r.URL.Query().Get("m")与r.URL.Query()["m"]的区别。一个只返回第一个参数的值,一个返回相同参数的所有值。
上一篇:
通过多线程提高代码的执行效率例子
下一篇:
校园一卡通的实现机制(图解)