幾個(gè)重要的變量
http.request 中涉及到數(shù)據(jù)解析的幾個(gè)重要變量為:
// Form contains the parsed form data, including both the URL
// field's query parameters and the POST or PUT form data.
// This field is only available after ParseForm is called.
// The HTTP client ignores Form and uses Body instead.
Form url.Values
// PostForm contains the parsed form data from POST, PATCH,
// or PUT body parameters.
//
// This field is only available after ParseForm is called.
// The HTTP client ignores PostForm and uses Body instead.
PostForm url.Values
// MultipartForm is the parsed multipart form, including file uploads.
// This field is only available after ParseMultipartForm is called.
// The HTTP client ignores MultipartForm and uses Body instead.
MultipartForm *multipart.Form
說(shuō)明:
Form:存儲(chǔ)了post、put和get參數(shù),在使用之前需要調(diào)用 ParseForm 方法。
PostForm:存儲(chǔ)了post、put參數(shù),在使用之前需要調(diào)用 ParseForm 方法。
MultipartForm:存儲(chǔ)了包含了文件上傳的表單的post參數(shù),在使用前需要調(diào)用 ParseMultipartForm
方法。
獲取 GET 參數(shù)
因?yàn)?Form 中同時(shí)存儲(chǔ)了 GET 和 POST 請(qǐng)求的參數(shù),所以最好不要用該變量來(lái)獲取 GET 參數(shù),取而代之的方法為:
queryForm, err := url.ParseQuery(r.URL.RawQuery)
if err == nil && len(queryForm["id"]) > 0 {
fmt.Fprintln(w, queryForm["id"][0])
}
獲取 POST 參數(shù)
application/x-www-form-urlencoded 格式
r.ParseForm()
// 法一
r.PostForm["id"][0]
// 法二
r.PostFormValue["id"]
multipart/form-data 格式
普通參數(shù)
r.ParseMultipartForm(32<<20)
// 法一
r.PostForm["id"][0]
// 法二
r.PostFormValue["id"]
文件
r.ParseMultipartForm(32 << 20)
file, handler, err := r.FormFile("file")
if err != nil {
fmt.Println(err)
return
}
defer file.Close()
fmt.Fprintf(w, "%v", handler.Header)
f, err := os.OpenFile("./test.txt", os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
fmt.Println(err)
return
}
defer f.Close()
io.Copy(f, file)
application/json 格式
type User struct {
Name string `json:"username"`
Pwd string `json:"password"`
}
type RetMessage struct {
Code string `json:"code"`
Msg string `json:"msg"`
}
func processJson(w http.ResponseWriter, r *http.Request) {
var u User
if r.Body == nil {
http.Error(w, "Please send a request body", 400)
return
}
err := json.NewDecoder(r.Body).Decode(&u)
if err != nil {
http.Error(w, err.Error(), 400)
return
}
fmt.Println(u)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(RetMessage{"200", "ok"})
}