英文:
Send JSON request to test Endpoint API in beego is failing with empty body
问题
我正在尝试使用beego框架测试我的REST API的端点。
下面是我使用的发送JSON请求的测试函数:
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()
}
服务器确实接收到请求,但请求的输入体始终为空。
类似地,我使用以下函数将表单数据发送到服务器,它可以正常工作:
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()
}
问题:为什么服务器接收到的JSON请求体为空,而类似的表单编码数据却正常工作?我已经困扰了几天,非常感谢任何指点。
英文:
I am trying to test the endpoint of my REST API's using beego framework.
My test function is below that I am using to send JSON request:
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()
}
The server does receive the request but the input body is always empty
for the request.
Similar, function that I am using to send Form data to server 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()
}
Issue: Why is the server receiving JSON request body as empty while similar form-encoded data goes fine. Have been stuck on this for a few days now, any pointers are highly appreciated.
答案1
得分: 0
在Beego中,默认情况下禁用了读取请求体的功能。你需要在app.conf
文件中添加以下行:
copyrequestbody = true
这样可以解决该问题。
英文:
Reading the body of a request is Disabled by default in Beego. You need to add the following line to app.conf
file
copyrequestbody = true
This resolves the issue.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论