6

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.

1
  • 1
    Here are docs for LimitReader Commented Nov 17, 2015 at 20:48

2 Answers 2

11

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Yikes, totally missed http.MaxBytesReader although it's there from (at least) Go 1.0! Thanks, need to update some of my LimitedReader use cases now.
-1

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.

1 Comment

I didn't downvote, but in case you didn't read @Cerise's answer: Checking the request content length is unreliable because the field is not set to the actual request body size when chunked encoding is used.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.