Standard library / net/http
http.MaxBytesHandler()
Wraps a handler with a request body limit. The inner handler must still handle the resulting read error and choose the status. Expected stdout: '413\n'.
Formal Syntax & Structure
go syntaxgo
func MaxBytesHandler(h Handler, n int64) HandlerParameters & Attributes
| Name | Type | Description |
|---|---|---|
| h | Handler | Handler to wrap or register. |
| n | int64 | Maximum number of incoming body bytes. |
Return Value
Handler
Operation result; check errors and validity indicators when returned.
Working Example
Example Snippetgo
package main
import ( "fmt" "io" "net/http" "net/http/httptest" "strings")
func main() { h := http.MaxBytesHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _, e := io.ReadAll(r.Body) if e != nil { http.Error(w, "too large", 413) return } fmt.Fprint(w, "ok") }), 3) w := httptest.NewRecorder() h.ServeHTTP(w, httptest.NewRequest("POST", "/", strings.NewReader("abcdef"))) fmt.Println(w.Code)}
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) }}