Skip to content

Commit 90286c7

Browse files
authored
fix: [#528] GraphQL request causing errors from request body parsing (#107)
1 parent 09d5160 commit 90286c7

File tree

2 files changed

+27
-5
lines changed

2 files changed

+27
-5
lines changed

context_request.go

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ type ContextRequest struct {
3434
func NewContextRequest(ctx *Context, log log.Log, validation contractsvalidate.Validation) contractshttp.ContextRequest {
3535
postData, err := getPostData(ctx)
3636
if err != nil {
37-
LogFacade.Error(fmt.Sprintf("%+v", errors.Unwrap(err)))
37+
LogFacade.Error(fmt.Sprintf("%+v", err))
3838
}
3939

4040
return &ContextRequest{ctx: ctx, instance: ctx.instance, postData: postData, log: log, validation: validation}
@@ -472,11 +472,13 @@ func getPostData(ctx *Context) (map[string]any, error) {
472472
return nil, fmt.Errorf("retrieve json error: %v", err)
473473
}
474474

475-
if err := json.Unmarshal(bodyBytes, &data); err != nil {
476-
return nil, fmt.Errorf("decode json [%v] error: %v", string(bodyBytes), err)
477-
}
475+
if len(bodyBytes) > 0 {
476+
if err := json.Unmarshal(bodyBytes, &data); err != nil {
477+
return nil, fmt.Errorf("decode json [%v] error: %v", string(bodyBytes), err)
478+
}
478479

479-
request.Body = io.NopCloser(bytes.NewBuffer(bodyBytes))
480+
request.Body = io.NopCloser(bytes.NewBuffer(bodyBytes))
481+
}
480482
}
481483

482484
if contentType == "multipart/form-data" {

context_request_test.go

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -983,6 +983,26 @@ func (s *ContextRequestSuite) TestInputBool() {
983983
s.Equal(http.StatusOK, code)
984984
}
985985

986+
// Test Issue: https://github.com/goravel/goravel/issues/528
987+
func (s *ContextRequestSuite) TestPostWithEmpty() {
988+
s.route.Post("/post-with-empty", func(ctx contractshttp.Context) contractshttp.Response {
989+
return ctx.Response().Success().Json(contractshttp.Json{
990+
"all": ctx.Request().All(),
991+
})
992+
})
993+
994+
payload := strings.NewReader("")
995+
req, err := http.NewRequest("POST", "/post-with-empty?a=1", payload)
996+
req.ContentLength = 1
997+
s.Require().Nil(err)
998+
999+
req.Header.Set("Content-Type", "application/json")
1000+
code, body, _, _ := s.request(req)
1001+
1002+
s.Equal("{\"all\":{\"a\":\"1\"}}", body)
1003+
s.Equal(http.StatusOK, code)
1004+
}
1005+
9861006
func (s *ContextRequestSuite) TestQuery() {
9871007
s.route.Get("/query", func(ctx contractshttp.Context) contractshttp.Response {
9881008
return ctx.Response().Success().Json(contractshttp.Json{

0 commit comments

Comments
 (0)