# Go Panics and Concurrency Bugs > Go turns many bugs into runtime panics, and `net/http` recovers them per request. That stops a crash but leaves locks held and invariants half-applied, so one bad request can become a persistent denial of service or a logic flaw. Data races are not prevented by the language. ## How it works `net/http` runs each request in its own goroutine and recovers handler panics. The client sees `curl: (52) Empty reply from server` and other handlers keep working. That isolation covers the stack, not shared state. Anything the panicking goroutine mutated or locked stays that way. Common panic sources reachable from input: - Index or slice out of range (`s[len(s)]`, `strings.Fields(out)[0]` on empty output) - Unchecked type assertion (`v.(int)` on a JSON `float64`) - Write to a nil map - Send on a closed channel - Nil pointer dereference, including a typed-nil inside an interface - Integer divide by zero (gopter surfaced this in Trail of Bits' example) ## Failure patterns ### Recovered panic, held lock (deadlock DoS) ```go func (t *Thing) AddComment(s string) { t.Lock() last := t.comments[len(t.comments)] // panics ... t.Unlock() // never runs } ``` The first request returns an empty reply. Every later request that touches `thing` blocks forever. From outside, it's a one-request DoS of that feature or of the whole service. `defer t.Unlock()` fixes the lock, but it is often omitted when there's no early return, and `defer` is function-scoped, so the critical section must be extracted into its own function. ### Recovered panic, broken invariant Even with `defer Unlock()`, state can be half-updated. In the `ByteCache.Put` example, `currSize += len(data)` runs before the panic and `cache[key] = data` never does. The size accounting is now permanently wrong (quota bypass or exhaustion). Rolling back partial mutations in a recover handler is rarely done correctly. Trail of Bits' **on-edge** tool targets exactly this: it records global state changes between function entry and a panic and reports them through the race detector. ### `recover()` scoping `recover()` only works when called **directly** in a deferred function. A `recover()` inside a helper called from the deferred closure returns `nil` and the panic continues. `if err := recover(); err != nil` also doesn't catch every panic (Unexpected Go). ### Error ignored, later panic In Kubernetes/cAdvisor, a faulted `ionice` read was logged, then `strings.Fields(stdout)[0]` panicked on empty output. KRF syscall fault injection found it. The general lesson is that error paths are where panics hide, so test them by forcing errors. ### Process-terminating calls `log.Fatal*` calls `os.Exit` and `log.Panic*` panics. A `log.Fatal` on a request-reachable error path is a remote kill switch. ### Data races - Built-in maps and slices are **not** synchronized. Concurrent map writes from handlers need a `sync.Mutex`/`RWMutex` or channel ownership. - **Loop-variable capture:** goroutines started in `for i := range` loops share the iteration variable (the notes describe the classic shared-variable loop semantics). Pass it as an argument or rebind with `i := i`. - `reflect` misuse (setting an unsettable value) panics at runtime (Snyk). - The app exits when `main` returns, regardless of active goroutines, so work can be silently dropped. ## Testing - Always run tests with `-race`. It doesn't find every concurrency bug, but it is cheap and catches real ones. Race-instrumented builds also help an attacker confirm exploitable races. - Grep for `.Lock()` lines not followed by `defer .Unlock()`, and for `recover()` calls not at the top of a deferred func. - Fuzz handlers (go-fuzz) and property-test stateful components (`gopter/commands`), checking invariants after each recovered panic. - Use fault injection (KRF) on code that shells out or does I/O. ## Defenses - Validate lengths and indices, and use `v, ok :=` for assertions and map lookups. - Always pair `Lock` with `defer Unlock` in a dedicated function. Make critical sections apply their changes only at the end (compute first, commit last). - Return errors up the stack instead of `log.Fatal` in library or handler code. ## Related - [[Go Security]] (hub) · [[Go Secure Coding Pitfalls]] · [[Go Security Testing Tools]] - [[GraphQL Denial of Service]] · [[API Rate Limiting]] ## Sources - [[raw/iximiuz.com/go-http-handlers-panic-and-deadlocks-1304|Go, HTTP handlers, panic, and deadlocks]] - [[raw/blog.trailofbits.com/security-assessment-techniques-for-go-projects-trail-of-bits-blog-1213|Security assessment techniques for Go projects]] - [[raw/devs.cloudimmunity.com/50-shades-of-go-traps-gotchas-and-common-mistakes-for-new-golang-devs-1102|50 Shades of Go: Traps, Gotchas, and Common Mistakes]] - [[raw/link.medium.com/the-top-10-most-common-mistakes-i-ve-seen-in-go-projects-1366|The Top 10 Most Common Mistakes I've Seen in Go Projects]] - [[raw/deepsource.io/5-common-mistakes-in-go-1275|5 Common mistakes in Go]] - [[raw/unexpected-go.com/unexpected-go-1115|Unexpected Go]] - [[raw/link.medium.com/go-how-does-a-program-recover-1321|Go: How Does a Program Recover?]] - [[raw/link.medium.com/error-handling-in-golang-with-panic-defer-and-recover-1343|Error Handling in Golang with Panic, Defer, and Recover]] - [[raw/snyk.io/go-security-cheatsheet-snyk-blog-1225|Go Security cheatsheet]]