go
network_error
ai_generated
true
WARNING: DATA RACE: Write by goroutine X, Read by goroutine Y (http.Handler)
ID: go/goroutine-http-server-race
80%Fix Rate
88%Confidence
0Evidence
2025-11-15First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 1.0 | active | — | — | — |
| 1.21 | active | — | — | — |
Root Cause
Multiple HTTP handler goroutines accessing shared state without synchronization.
generic中文
多个HTTP处理程序协程在没有同步的情况下访问共享状态。
Workarounds
-
95% success Use local variables within handler
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { var counter int counter++ fmt.Fprintf(w, "%d", counter) }) -
90% success Use sync.Mutex for shared state
var mu sync.Mutex var counter int http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { mu.Lock() counter++ mu.Unlock() fmt.Fprintf(w, "%d", counter) })
Dead Ends
Common approaches that don't work:
-
Using global variables for request state
90% fail
Global variables are shared across all requests; race condition.
-
Using request-scoped variables incorrectly
70% fail
If variable is captured by closure, it may be shared.