3

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.

Mario Pérez Alarcón
  • 3,468
  • 2
  • 27
  • 38
lionelmessi
  • 1,116
  • 2
  • 10
  • 17
  • I am having similar problem , my `copyrequestbody` is set to `true` I dont see a request doing to server at all , but somehow the response is empty – poorva Apr 29 '16 at 05:26
  • your req is not reaching the server? – lionelmessi Apr 29 '16 at 15:34
  • i belive that a `ListenAndServe` method is internally called in this case. The only factor by which i can say that the server is running properly is if i make a valid request i get 200 OK but for invalid requests i get 404 Actually , I have posted my actual problem [here](http://stackoverflow.com/questions/36983078/beego-endpoint-testing) – poorva May 02 '16 at 13:00
  • I get unmatch GET to my URL and it returns 404 status , but infact using Postman I get response [here](http://stackoverflow.com/questions/40130473/beego-test-case-returns-404-status-endpoint-not-match) – souravlahoti Oct 19 '16 at 12:12

1 Answers1

0

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.

lionelmessi
  • 1,116
  • 2
  • 10
  • 17