-1

I've written a logger middleware which stores incoming GraphQL requests info. The problem is if I try to read the request body, I get the following 400 Bad Request:

{
    "errors": [
        {
            "message": "json body could not be decoded: EOF"
        }
    ],
    "data": null
}

My code:

clonedReq := r.Clone(ctx)
data, _ := io.ReadAll(clonedReq.Body)

// store the data...
fmt.Println(string(data))

The data is displayed, but then I face the EOF error. If I comment this part out, the request is responded without any problems.

With or without a deep copy of the request with Clone, the issue persists.

H.Yazdani
  • 65
  • 3

1 Answers1

3

The middleware reads the request body to EOF. The handler encounters the EOF. The contents of the request body is not cloned in Clone().

To fix the code, restore the request body in the middleware:

  data, _ := io.ReadAll(r.Body)
  r.Body = io.NopCloser(bytes.NewReader(data))
  • r.Body is of type `io.ReadCloser`, where as NewReader does not have the method `Close()`. Any way to assign one to the other one? Edit: Wrap NewReader in `io.NopCloser` – H.Yazdani Feb 10 '23 at 17:16