Standard library / net/http
http.MaxBytesReader()
Limits incoming body bytes and returns a MaxBytesError when reading beyond the limit. Close the returned reader. Expected stdout: 'abc true\n'.
Formal Syntax & Structure
go syntaxgo
func MaxBytesReader(w ResponseWriter, r io.ReadCloser, n int64) io.ReadCloserParameters & Attributes
| Name | Type | Description |
|---|---|---|
| w | ResponseWriter | Destination writer. |
| r | io.ReadCloser | Source reader. |
| n | int64 | Maximum number of incoming body bytes. |
Return Value
io.ReadCloser
Operation result; check errors and validity indicators when returned.
Working Example
Example Snippetgo
package main
import ( "errors" "fmt" "io" "net/http" "net/http/httptest" "strings")
func main() { r := httptest.NewRequest("POST", "/", strings.NewReader("abcdef")) b := http.MaxBytesReader(httptest.NewRecorder(), r.Body, 3) defer b.Close() data, e := io.ReadAll(b) var limit *http.MaxBytesError fmt.Println(string(data), errors.As(e, &limit))}
func must[T any](v T, e error) T { if e != nil { panic(e) } return v}func check(e error) { if e != nil { panic(e) }}