Skip to content

Commit f136047

Browse files
authored
Use and update GetBody() member of request (#704)
1 parent 8718011 commit f136047

File tree

2 files changed

+27
-2
lines changed

2 files changed

+27
-2
lines changed

openapi3filter/validate_request.go

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import (
55
"context"
66
"errors"
77
"fmt"
8+
"io"
89
"io/ioutil"
910
"net/http"
1011
"sort"
@@ -216,7 +217,19 @@ func ValidateRequestBody(ctx context.Context, input *RequestValidationInput, req
216217
}
217218
}
218219
// Put the data back into the input
219-
req.Body = ioutil.NopCloser(bytes.NewReader(data))
220+
req.Body = nil
221+
if req.GetBody != nil {
222+
if req.Body, err = req.GetBody(); err != nil {
223+
req.Body = nil
224+
}
225+
}
226+
if req.Body == nil {
227+
req.ContentLength = int64(len(data))
228+
req.GetBody = func() (io.ReadCloser, error) {
229+
return io.NopCloser(bytes.NewReader(data)), nil
230+
}
231+
req.Body, _ = req.GetBody() // no error return
232+
}
220233
}
221234

222235
if len(data) == 0 {
@@ -292,8 +305,14 @@ func ValidateRequestBody(ctx context.Context, input *RequestValidationInput, req
292305
}
293306
}
294307
// Put the data back into the input
295-
req.Body = ioutil.NopCloser(bytes.NewReader(data))
308+
if req.Body != nil {
309+
req.Body.Close()
310+
}
296311
req.ContentLength = int64(len(data))
312+
req.GetBody = func() (io.ReadCloser, error) {
313+
return io.NopCloser(bytes.NewReader(data)), nil
314+
}
315+
req.Body, _ = req.GetBody() // no error return
297316
}
298317

299318
return nil

openapi3filter/validate_request_test.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -212,6 +212,12 @@ components:
212212
assert.Equal(t, contentLen, bodySize, "expect ContentLength %d to equal body size %d", contentLen, bodySize)
213213
bodyModified := originalBodySize != bodySize
214214
assert.Equal(t, bodyModified, tc.expectedModification, "expect request body modification happened: %t, expected %t", bodyModified, tc.expectedModification)
215+
216+
validationInput.Request.Body, err = validationInput.Request.GetBody()
217+
assert.NoError(t, err, "unable to re-generate body by GetBody(): %v", err)
218+
body2, err := io.ReadAll(validationInput.Request.Body)
219+
assert.NoError(t, err, "unable to read request body: %v", err)
220+
assert.Equal(t, body, body2, "body by GetBody() is not matched")
215221
})
216222
}
217223
}

0 commit comments

Comments
 (0)