Go: 使用PUT發(fā)送Form Data

我使用Go實現(xiàn)了一個PUT接口,在瀏覽器中可以使用ajax發(fā)送請求:

            $.ajax({
                url: "/api/accounts/" + email + "/",   // Append back slash for put request
                type: "PUT",
                data: {"password": password, "name": name},
                error: function(resp, status, error) {
                    let msg = resp.responseText;
                    if(status == 500) {
                        msg = "Internal error"
                    }

但是使用Go寫test時,發(fā)送的請求卻接收不到了:

            values := url.Values {
                "name": { "ethan" },
                "password": { "password" },
            }
            req, err := http.NewRequest("PUT", urlPath, strings.NewReader(values.Encode()))
            if err != nil {
                t.Fatalf("%d: NewRequest failed with error: %s", i, err)
            }
            client := http.Client{}
            resp, err := client.Do(req)

最終在request.go:ParseForm()函數(shù)中找到了答案:
FormValue可以處理url中的query鍵值對,對于PUT/POST/PATCH請求,也會將body中的內(nèi)容處理成鍵值對,但Content-Type要設(shè)置成application/x-www-form-urlencoded,因此只要在request中添加這個header即可:

            req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
            client := http.Client{}
            resp, err := client.Do(req)

注釋原文:

// ParseForm populates r.Form and r.PostForm.
//
// For all requests, ParseForm parses the raw query from the URL and updates
// r.Form.
//
// For POST, PUT, and PATCH requests, it also parses the request body as a form
// and puts the results into both r.PostForm and r.Form. Request body parameters
// take precedence over URL query string values in r.Form.
//
// For other HTTP methods, or when the Content-Type is not
// application/x-www-form-urlencoded, the request Body is not read, and
// r.PostForm is initialized to a non-nil, empty value.
//
// If the request Body's size has not already been limited by MaxBytesReader,
// the size is capped at 10MB.
//
// ParseMultipartForm calls ParseForm automatically.
// ParseForm is idempotent.
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

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

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