| 1 |
package s1035 |
| 2 |
|
| 3 |
import ( |
| 4 |
"fmt" |
| 5 |
"go/ast" |
| 6 |
|
| 7 |
"honnef.co/go/tools/analysis/code" |
| 8 |
"honnef.co/go/tools/analysis/edit" |
| 9 |
"honnef.co/go/tools/analysis/facts/generated" |
| 10 |
"honnef.co/go/tools/analysis/lint" |
| 11 |
"honnef.co/go/tools/analysis/report" |
| 12 |
"honnef.co/go/tools/pattern" |
| 13 |
|
| 14 |
"golang.org/x/tools/go/analysis" |
| 15 |
) |
| 16 |
|
| 17 |
var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ |
| 18 |
Analyzer: &analysis.Analyzer{ |
| 19 |
Name: "S1035", |
| 20 |
Run: run, |
| 21 |
Requires: append([]*analysis.Analyzer{generated.Analyzer}, code.RequiredAnalyzers...), |
| 22 |
}, |
| 23 |
Doc: &lint.RawDocumentation{ |
| 24 |
Title: `Redundant call to \'net/http.CanonicalHeaderKey\' in method call on \'net/http.Header\'`, |
| 25 |
Text: ` |
| 26 |
The methods on \'net/http.Header\', namely \'Add\', \'Del\', \'Get\' |
| 27 |
and \'Set\', already canonicalize the given header name.`, |
| 28 |
Since: "2020.1", |
| 29 |
MergeIf: lint.MergeIfAny, |
| 30 |
}, |
| 31 |
}) |
| 32 |
|
| 33 |
var Analyzer = SCAnalyzer.Analyzer |
| 34 |
|
| 35 |
var query = pattern.MustParse(` |
| 36 |
(CallExpr |
| 37 |
(Symbol |
| 38 |
callName@(Or |
| 39 |
"(net/http.Header).Add" |
| 40 |
"(net/http.Header).Del" |
| 41 |
"(net/http.Header).Get" |
| 42 |
"(net/http.Header).Set")) |
| 43 |
arg@(CallExpr (Symbol "net/http.CanonicalHeaderKey") _):_)`) |
| 44 |
|
| 45 |
func run(pass *analysis.Pass) (any, error) { |
| 46 |
for _, m := range code.Matches(pass, query) { |
| 47 |
arg := m.State["arg"].(*ast.CallExpr) |
| 48 |
report.Report(pass, m.State["arg"].(ast.Expr), |
| 49 |
fmt.Sprintf("calling net/http.CanonicalHeaderKey on the 'key' argument of %s is redundant", m.State["callName"].(string)), |
| 50 |
report.FilterGenerated(), |
| 51 |
report.Fixes(edit.Fix("Remove call to CanonicalHeaderKey", edit.ReplaceWithNode(pass.Fset, arg, arg.Args[0])))) |
| 52 |
} |
| 53 |
return nil, nil |
| 54 |
} |