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

Also available as: JSON · Markdown · 中文
80%Fix Rate
88%Confidence
0Evidence
2025-11-15First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.0 active
1.21 active

Root Cause

Multiple HTTP handler goroutines accessing shared state without synchronization.

generic

中文

多个HTTP处理程序协程在没有同步的情况下访问共享状态。

Workarounds

  1. 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)
    })
  2. 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:

  1. Using global variables for request state 90% fail

    Global variables are shared across all requests; race condition.

  2. Using request-scoped variables incorrectly 70% fail

    If variable is captured by closure, it may be shared.