Limiting upload size

When it sounds counter-intuitive to limit the upload size, it is actually a good practice to do so. Limiting the upload size can prevent the server from being overwhelmed by a large file upload which can take a lot of resources, take longer to finish, increase the possibility of failures during the upload, and increase the risk of denial of service attack.

In go, doing this is quite simple. You can use the http.MaxBytesReader to limit the size of the request body.

func BinaryUpload() http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        r.Body = http.MaxBytesReader(w, r.Body, 10<<20) //10MB
        defer r.Body.Close()
        
        // the rest of the code ...
    }
}

In the code above, we limit the size of the request body to 10MB. When the request body exceeds the limit, the server will return http.StatusRequestEntityTooLarge status code to the client.

Now, you must be wondering if we limit the size of the request body, how can we handle the file upload that exceeds the limit?

There are several ways to handle this. One of them is by chunking the file upload. Instead of uploading the entire file at once, client splits the file into smaller chunks and upload them all either in parallel or in series. More on this will be discussed later in the course.