Request是HTTP訪問的請求對象,非常重要的一部分,正確的解析請求數據才能給客戶端返回響應。
通過標準庫瞭解到該結構的詳細組成,通過簡單示例驗證一下。
下方是go服務端代碼,解析Request各成員,或者說是屬性。
// sayhello project sayhello.go
package main
import (
"fmt"
"log"
"net/http"
"strings"
)
func sayhello(w http.ResponseWriter, r *http.Request) {
// r.ParseForm() //解析參數,默認是不會解析的
//這些信息是輸出到服務器端的打印信息
fmt.Println("Request解析")
//HTTP方法
fmt.Println("method", r.Method)
// RequestURI是被客戶端發送到服務端的請求的請求行中未修改的請求URI
fmt.Println("RequestURI", r.RequestURI)
//URL類型,下方分別列出URL的各成員
fmt.Println("URL_scheme", r.URL.Scheme)
fmt.Println("URL_opaque", r.URL.Opaque)
fmt.Println("URL_user", r.URL.User.String())
fmt.Println("URL_host", r.URL.Host)
fmt.Println("URL_path", r.URL.Path)
fmt.Println("URL_RawQuery", r.URL.RawQuery)
fmt.Println("URL_Fragment", r.URL.Fragment)
//協議版本
fmt.Println("proto", r.Proto)
fmt.Println("protomajor", r.ProtoMajor)
fmt.Println("protominor", r.ProtoMinor)
//HTTP請求的頭域
for k, v := range r.Header {
// fmt.Println("Header key:" + k)
for _, vv := range v {
fmt.Println("header key:" + k + " value:" + vv)
}
}
//判斷是否multipart方式
is_multipart := false
for _, v := range r.Header["Content-Type"] {
if strings.Index(v, "multipart/form-data") != -1 {
is_multipart = true
}
}
//解析body
if is_multipart == true {
r.ParseMultipartForm(128)
fmt.Println("解析方式:ParseMultipartForm")
} else {
r.ParseForm()
fmt.Println("解析方式:ParseForm")
}
//body內容長度
fmt.Println("ContentLength", r.ContentLength)
//是否在回覆請求後關閉連接
fmt.Println("Close", r.Close)
//HOSt
fmt.Println("host", r.Host)
//form
fmt.Println("Form", r.Form)
//postform
fmt.Println("PostForm", r.PostForm)
//MultipartForm
fmt.Println("MultipartForm", r.MultipartForm)
//該請求的來源地址
fmt.Println("RemoteAddr", r.RemoteAddr)
for k, v := range r.Form {
fmt.Println("key:", k)
fmt.Println("value:", strings.Join(v, ""))
}
fmt.Fprintf(w, "hello astaxie!") //這個寫入到w的是輸出到客戶端的
}
func main() {
http.HandleFunc("/", sayhello)
err := http.ListenAndServe(":9090", nil)
if err != nil {
log.Fatal("ListenAndServe:", err)
}
}
1、先實驗application/x-www-form-urlencoded類型的,get請求,通過postman發送請求
服務端接收到的數據
可以接收到請求方法、URL內待的查詢參數,basicauth認證信息,不過URL的user不清楚是做什麼用的
2、實驗application/x-www-form-urlencoded類型的,post請求,增加body內容,其他不變,通過postman發送請求,
服務端接收到的數據
可以接收到請求方法,post,form內既包含查詢參數、也包含body內的參數,postform,只包含body內的參數