Go 網(wǎng)絡(luò)編程:解析請(qǐng)求數(shù)據(jù)

幾個(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"})
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容