我正在嘗試使用 beego 框架測試我的 REST API 的端點。我的測試函數(shù)低于我用來發(fā)送 JSON 請求的函數(shù):func testHTTPJsonResp(url string) string { var jsonStr = []byte(`{"title":"Buy cheese and bread for breakfast."}`) req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr)) req.Header.Set("X-Custom-Header", "myvalue") req.Header.Set("Content-Type", "application/json") beego.Error(err) w := httptest.NewRecorder() beego.BeeApp.Handlers.ServeHTTP(w, req) beego.Debug(w) return w.Body.String()}服務(wù)器確實收到請求,但輸入正文始終empty用于請求。類似的,我用來將表單數(shù)據(jù)發(fā)送到服務(wù)器的函數(shù)works fine。func testHTTPResp(httpProt, url string, params map[string]interface{}) string { bodyBuf := &bytes.Buffer{} bodyWriter := multipart.NewWriter(bodyBuf) for key, val := range params { beego.Error(key + val.(string)) _ = bodyWriter.WriteField(key, val.(string)) } contentType := bodyWriter.FormDataContentType() bodyWriter.Close() r, _ := http.NewRequest(httpProt, url, bodyBuf) r.Header.Add("Content-Type", contentType) w := httptest.NewRecorder() beego.BeeApp.Handlers.ServeHTTP(w, r) beego.Debug(w) return w.Body.String()}問題:為什么服務(wù)器接收 JSON 請求正文為空,而類似的表單編碼數(shù)據(jù)正常。已經(jīng)堅持了幾天了,任何指針都非常感謝。
1 回答

慕后森
TA貢獻1802條經(jīng)驗 獲得超5個贊
在 Beego 中默認禁用讀取請求正文。您需要將以下行添加到app.conf
文件中
copyrequestbody = true
這解決了這個問題。
- 1 回答
- 0 關(guān)注
- 196 瀏覽
添加回答
舉報
0/150
提交
取消