mirror of
https://github.com/imjasonh/ctxhttp-analyzer
synced 2026-07-06 22:12:38 +00:00
Go analyzer that detects net/http calls without context and rewrites them to use http.NewRequestWithContext. Handles http.Get/Post/Head/PostForm, client methods, and injects context at function boundaries (main, tests, HTTP handlers). Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
1.6 KiB
1.6 KiB
ctxhttp-analyzer
Go analyzer that detects HTTP calls without context and suggests fixes to use http.NewRequestWithContext.
Architecture
Uses go/analysis.Analyzer with SuggestedFix text edits. Run via singlechecker.Main so it works as a standalone tool or with go vet -vettool.
Single-package scope — compile errors from missing ctx guide users to plumb context through their call chains.
What we detect and rewrite
| Before | After |
|---|---|
http.NewRequest(m, u, b) |
http.NewRequestWithContext(ctx, m, u, b) |
http.Get(url) |
NewRequestWithContext + http.DefaultClient.Do(req) |
http.Post(url, ct, body) |
NewRequestWithContext + set Content-Type + http.DefaultClient.Do(req) |
http.Head(url) |
NewRequestWithContext + http.DefaultClient.Do(req) |
http.PostForm(url, data) |
NewRequestWithContext + set Content-Type + http.DefaultClient.Do(req) |
client.Get/Post/Head/PostForm |
Same but client.Do(req) |
Context injection
Where does ctx come from?
- Function already has
context.Contextparam → use it (whatever name) main()/init()→ctx := context.Background()TestXxx/BenchmarkXxx→ctx := context.Background()- HTTP handler
(w http.ResponseWriter, r *http.Request)→ctx := r.Context() - Otherwise →
ctx := context.TODO()
Known limitations
- Multi-statement rewrites (Get/Post/etc.) generate
return errin error checks, which may not match the function's return signature - Interface method signatures: not handled
- Cross-module callers: can't propagate context