Skip to content

Commit

Permalink
Merge pull request #53 from vsvastey/usr/vsvastey/switchstmt
Browse files Browse the repository at this point in the history
feat: add check HTTP Method and HTTP Status is SwitchStmt
  • Loading branch information
sashamelentyev committed Aug 20, 2022
2 parents 87d3556 + 61bb831 commit 1796d3a
Show file tree
Hide file tree
Showing 5 changed files with 1,215 additions and 0 deletions.
38 changes: 38 additions & 0 deletions pkg/analyzer/analyzer.go
Expand Up @@ -54,6 +54,7 @@ func run(pass *analysis.Pass) (interface{}, error) {
(*ast.BasicLit)(nil),
(*ast.CompositeLit)(nil),
(*ast.IfStmt)(nil),
(*ast.SwitchStmt)(nil),
}

insp.Preorder(filter, func(node ast.Node) {
Expand Down Expand Up @@ -224,6 +225,43 @@ func run(pass *analysis.Pass) (interface{}, error) {

checkHTTPMethod(pass, basicLit)
}

case *ast.SwitchStmt:
selectorExpr, ok := n.Tag.(*ast.SelectorExpr)
if !ok {
return
}

var checkFunc func(pass *analysis.Pass, basicLit *ast.BasicLit)

switch selectorExpr.Sel.Name {
case "StatusCode":
if !lookupFlag(pass, HTTPStatusCodeFlag) {
return
}
checkFunc = checkHTTPStatusCode
case "Method":
if !lookupFlag(pass, HTTPMethodFlag) {
return
}
checkFunc = checkHTTPMethod
default:
return
}

for _, stmt := range n.Body.List {
caseClause, ok := stmt.(*ast.CaseClause)
if !ok {
continue
}
for _, expr := range caseClause.List {
basicLit, ok := expr.(*ast.BasicLit)
if !ok {
continue
}
checkFunc(pass, basicLit)
}
}
}
})

Expand Down
20 changes: 20 additions & 0 deletions pkg/analyzer/internal/template/test-httpmethod.go.tmpl
Expand Up @@ -63,3 +63,23 @@ func _() error {
return nil
}
{{ end -}}

{{ range $key, $value := .Mapping }}
func _() {
var r http.Request
switch r.Method {
case "{{ $key }}": // want `"{{ quoteMeta $key }}" can be replaced by {{ quoteMeta $value }}`
return
}
}
{{ end -}}

{{ range $key, $value := .Mapping }}
func _() {
var r http.Request
switch r.Method {
case {{ $value }}:
return
}
}
{{ end -}}
21 changes: 21 additions & 0 deletions pkg/analyzer/internal/template/test-httpstatuscode.go.tmpl
Expand Up @@ -126,3 +126,24 @@ func _() {
http.RedirectHandler("", {{ $value }})
}
{{ end -}}


{{ range $key, $value := .Mapping }}
func _() {
var resp http.Response
switch resp.StatusCode {
case {{ $key }}: // want `"{{ quoteMeta $key }}" can be replaced by {{ quoteMeta $value }}`
return
}
}
{{ end -}}

{{ range $key, $value := .Mapping }}
func _() {
var resp http.Response
switch resp.StatusCode {
case {{ $value }}:
return
}
}
{{ end -}}
144 changes: 144 additions & 0 deletions pkg/analyzer/testdata/src/a/http/method.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 1796d3a

Please sign in to comment.