2
我试图使用beego框架测试我的REST API的端点。发送JSON请求以测试beego中的端点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()
}
服务器确实接收到请求,但输入的身体总是empty
的请求。
类似的,我用来将表单数据发送到服务器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()
}
问题:为什么服务器接收JSON请求体为空,而类似的形式编码数据变为正常。现在已经停留了几天,任何指针都非常感谢。
我有类似的问题,我的'copyrequestbody'设置为'true' 我没有看到请求对服务器做任何请求,但不知何故响应为空 – poorva
您的请求没有到达服务器? – lionelmessi
我相信在这种情况下,ListenAndServe方法在内部被调用。 我可以说服务器正常运行的唯一因素是,如果我提出了一个有效的请求,我得到200 OK,但对于无效请求,我得到了404 其实,我已经发布了我的实际问题[here](http:// stackoverflow.com/questions/36983078/beego-endpoint-testing) – poorva