/
analyzer.go
66 lines (61 loc) · 1.69 KB
/
analyzer.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package linter
import (
"go/ast"
"go/types"
"golang.org/x/tools/go/analysis"
"golang.org/x/tools/go/analysis/passes/inspect"
"golang.org/x/tools/go/ast/inspector"
)
var Analyzer = &analysis.Analyzer{
Name: "noDefaultHttpClient",
Doc: "noDefaultHttpClient restrict to use net/http.DefaultClient",
Run: run,
Requires: []*analysis.Analyzer{
inspect.Analyzer,
},
}
func run(pass *analysis.Pass) (interface{}, error) {
inspect := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector)
nodeFilter := []ast.Node{
(*ast.CallExpr)(nil),
(*ast.SelectorExpr)(nil),
}
inspect.Preorder(nodeFilter, func(n ast.Node) {
switch n := n.(type) {
case *ast.SelectorExpr:
pkgIdent, ok := n.X.(*ast.Ident)
if !ok {
return
}
pkgName, ok := pass.TypesInfo.Uses[pkgIdent].(*types.PkgName)
if !ok || pkgName.Imported().Path() != "net/http" {
return
}
if n.Sel.Name == "DefaultClient" {
pass.Reportf(n.Pos(), "Do not use net/http.%s because default client has no timeout", n.Sel.Name)
}
case *ast.CallExpr:
s, ok := n.Fun.(*ast.SelectorExpr)
if !ok {
return
}
pkgIdent, ok := s.X.(*ast.Ident)
if !ok {
return
}
pkgName, ok := pass.TypesInfo.Uses[pkgIdent].(*types.PkgName)
if !ok || pkgName.Imported().Path() != "net/http" {
return
}
switch s.Sel.Name {
case "Get":
pass.Reportf(n.Pos(), "Do not use net/http.%s because default client has no timeout", s.Sel.Name)
case "Post":
pass.Reportf(n.Pos(), "Do not use net/http.%s because default client has no timeout", s.Sel.Name)
case "PostForm":
pass.Reportf(n.Pos(), "Do not use net/http.%s because default client has no timeout", s.Sel.Name)
}
}
})
return nil, nil
}