# 警告：数据竞争：协程X写入，协程Y读取（http.Handler）

- **ID:** `go/goroutine-http-server-race`
- **领域:** go
- **类别:** network_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

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

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 1.0 | active | — | — |
| 1.21 | active | — | — |

## 解决方案

1. **Use local variables within handler** (95% 成功率)
   ```
   http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    var counter int
    counter++
    fmt.Fprintf(w, "%d", counter)
})
   ```
2. **Use sync.Mutex for shared state** (90% 成功率)
   ```
   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)
})
   ```

## 无效尝试

- **Using global variables for request state** — Global variables are shared across all requests; race condition. (90% 失败率)
- **Using request-scoped variables incorrectly** — If variable is captured by closure, it may be shared. (70% 失败率)
