英文:
Stop processing a http POST request if it is larger than x size
问题
如果我有一个用于处理POST请求的基本HTTP处理程序,如果负载大于100 KB,我该如何停止处理?
据我了解,在我的POST处理程序中,服务器在幕后流式传输POST的数据。但是,如果我尝试访问它,它会阻塞,对吗?我想在大小超过100 KB时停止处理。
英文:
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
得分: 11
使用http.MaxBytesReader来限制从客户端读取的数据量。在调用r.ParseForm、r.FormValue或任何其他读取请求体的请求方法之前,执行以下代码:
r.Body = http.MaxBytesReader(w, r.Body, 100000)
使用io.LimitedReader包装请求体可以限制应用程序读取的数据量,但不一定限制服务器代表应用程序读取的数据量。
检查请求内容长度是不可靠的,因为当使用分块编码时,该字段不会设置为实际请求体的大小。
英文:
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.
答案2
得分: -1
我相信你可以简单地检查http.Request.ContentLength
参数来了解发送的请求的大小,然后决定是否继续处理,或者如果超过预期大小就返回错误。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论