Bound HTTP and goroutine resources
Bound HTTP and goroutine resources
Security includes availability. A small request can require disproportionate memory, CPU or goroutines. Limit request bytes before decoding, enforce time budgets and restrict concurrent work. The sample handler accepts up to eight bytes to make the boundary easy to observe.
package main
import ( "errors" "fmt" "io" "net/http" "net/http/httptest" "strings")
func receive(w http.ResponseWriter, r *http.Request) { defer r.Body.Close() r.Body = http.MaxBytesReader(w, r.Body, 8) b, e := io.ReadAll(r.Body) if e != nil { var large *http.MaxBytesError if errors.As(e, &large) { http.Error(w, "too large", 413) } else { http.Error(w, "bad body", 400) } return } fmt.Fprint(w, len(b))}func main() { w := httptest.NewRecorder() receive(w, httptest.NewRequest("POST", "/", strings.NewReader("123456789"))) fmt.Println(w.Code)}MaxBytesReader returns an error when the stream exceeds the limit. Distinguish that error from other read failures. Also configure appropriate server ReadHeaderTimeout, read/write/idle timeouts, header limits and handler deadlines; choose values for your workload, especially streaming. Byte limits alone do not bound CPU or concurrent clients.
Expected output:
413Limit concurrent admission
package main
import ( "fmt")
func acquire(slots chan struct{}) bool { select { case slots <- struct{}{}: return true default: return false }}func main() { slots := make(chan struct{}, 1) fmt.Println(acquire(slots), acquire(slots)) <-slots fmt.Println(acquire(slots)) <-slots}Acquire a slot before launching work and release exactly once with defer after successful admission. The example chooses immediate rejection when full instead of an unbounded waiting queue. A service may return 503 with an appropriate retry policy. Context cancellation is cooperative; operations must observe it. Use both local and system-level resource limits.
Expected output:
true falsetrueTry it locally
Run the handler with exactly eight bytes and print its status and body.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Security engineering 04: Bound HTTP and goroutine resources
Check the lesson objective before moving on.
Where should a body limit be applied?
What should happen when the bounded gate is full in this design?