How to Use io.LimitReader to Prevent Memory Exhaustion

Use io.LimitReader to cap the number of bytes read from an io.Reader and prevent memory exhaustion.

Wrap your io.Reader with io.LimitReader to enforce a maximum byte count and prevent memory exhaustion. This wrapper stops reading once the limit is reached, returning io.EOF.

import "io"

// Limit reading to 10MB (10 * 1024 * 1024 bytes)
limitedReader := io.LimitReader(originalReader, 10*1024*1024)

// Read from limitedReader instead of originalReader
data, err := io.ReadAll(limitedReader)