skip to content
Alvin Lucillo

Limit memory exhaution attacks with LimitReader

/ 1 min read

💻 Tech

There are many ways to handle request body size in Go.

  1. http.MaxBytesReader — returns an error and handles response (with status code) if maximum request size is exceeded; specific to HTTP request only
  2. io.LimitReader — returns EOF once the limit is reached; can handle other IO readers, not only HTTP requests
func someoHandler(w http.ResponseWriter, r *http.Request) {
	defer r.Body.Close()

	// first method - http.MaxBytesReader 
	// Limit request body size to 1MB (1 << 20 bytes)
    // r.Body = http.MaxBytesReader(w, r.Body, 1<<20)

	// second method - io.LimitReader 
	rdr := io.LimitReader(r.Body, 1_000_000) // return EOF once 1MB is reached
	data, err := io.ReadAll(rdr)
	if err != nil {
		http.Error(w, "can't read", http.StatusBadRequest)
		return
	}

	resp := map[string]any{
		"result": processText(string(data)),
	}

	data, err = json.Marshal(resp)
	if err != nil {
		http.Error(w, "can't encode", http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "application/json")
	w.Write(data)
}