Reputation: 4811
If I have a basic http handler for POST requests, how can I stop processing if the payload is larger than 100 KB?
From what I understand, in my POST Handler, behind the scenes the server is streaming the POSTED data. But if I try and access it, it will block correct? I want to stop processing if it is over 100 KB in size.
Upvotes: 6
Views: 4181
Reputation: 120999
Use http.MaxBytesReader to limit the amount of data read from the client. Execute this line of code
r.Body = http.MaxBytesReader(w, r.Body, 100000)
before calling r.ParseForm, r.FormValue or any other request method that reads the body.
Wrapping the request body with io.LimitedReader limits the amount of data read by the application, but does not necessarily limit the amount of data read by the server on behalf of the application.
Checking the request content length is unreliable because the field is not set to the actual request body size when chunked encoding is used.
Upvotes: 11
Reputation: 6154
I believe you can simply check http.Request.ContentLength
param to know about the size of the posted request prior to decide whether to go ahead or return error if larger than expected.
Upvotes: -1