go
runtime_error
ai_generated
true
http:多余的 response.WriteHeader 调用,来自 main.handler(server.go:42)
http: superfluous response.WriteHeader call from main.handler (server.go:42)
ID: go/http-superfluous-writeheader
80%修复率
87%置信度
0证据数
2024-06-11首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 1.18 | active | — | — | — |
| 1.21 | active | — | — | — |
根因分析
WriteHeader 被调用多次,或在 WriteHeader 之前调用了 Write。只有第一个状态码会被发送。
English
WriteHeader is called more than once, or Write is called before WriteHeader. Only the first status code is sent.
解决方案
-
90% 成功率
if !wroteHeader { w.WriteHeader(http.StatusOK); wroteHeader = true } json.NewEncoder(w).Encode(v) -
88% 成功率
Return early after writing an error status; never write body after WriteHeader without checking.
无效尝试
常见但无效的做法:
-
80% 失败
Hides a real bug; the wrong status code may be sent to clients.
-
70% 失败
Does not fix the underlying control flow.