Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Request body too large causing connection reset in Go

I have a simple multipart form which uploads to a Go app. I wanted to set a restriction on the upload size, so I did the following:

func myHandler(rw http.ResponseWriter, request *http.Request){  
    request.Body = http.MaxBytesReader(rw, request.Body, 1024)
    err := request.ParseMultipartForm(1024)
    if err != nil{
    // Some response.
    } 
}  

Whenever an upload exceeds the maximum size, I get a connection reset like the following: enter image description here

and yet the code continues executing. I can't seem to provide any feedback to the user. Instead of severing the connection I'd prefer to say "You've exceeded the size limit". Is this possible?

like image 331
Sam Avatar asked Mar 14 '23 10:03

Sam


1 Answers

This code works as intended. Description of http.MaxBytesReader

MaxBytesReader is similar to io.LimitReader but is intended for limiting the size of incoming request bodies. In contrast to io.LimitReader, MaxBytesReader's result is a ReadCloser, returns a non-EOF error for a Read beyond the limit, and closes the underlying reader when its Close method is called.

MaxBytesReader prevents clients from accidentally or maliciously sending a large request and wasting server resources.

You could use io.LimitReader to read just N bytes and then do the handling of the HTTP request on your own.

like image 183
TheHippo Avatar answered Mar 24 '23 08:03

TheHippo