Search code examples
gobeego

Send JSON request to test Endpoint API in beego is failing with empty body


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.


Solution

  • 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.