Go: 使用PUT發送Form Data

我使用Go實現了一個PUT接口,在瀏覽器中可以使用ajax發送請求:

            $.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時,發送的請求卻接收不到了:

            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()函數中找到了答案:
FormValue可以處理url中的query鍵值對,對于PUT/POST/PATCH請求,也會將body中的內容處理成鍵值對,但Content-Type要設置成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.
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容