57 lines
1.2 KiB
Go
57 lines
1.2 KiB
Go
|
|
package request
|
||
|
|
|
||
|
|
import (
|
||
|
|
"go/ast"
|
||
|
|
"go/parser"
|
||
|
|
"go/token"
|
||
|
|
"reflect"
|
||
|
|
"strconv"
|
||
|
|
"strings"
|
||
|
|
"testing"
|
||
|
|
"unicode"
|
||
|
|
)
|
||
|
|
|
||
|
|
func TestRequestStructTagsUseSnakeCase(t *testing.T) {
|
||
|
|
fset := token.NewFileSet()
|
||
|
|
packages, err := parser.ParseDir(fset, ".", nil, 0)
|
||
|
|
if err != nil {
|
||
|
|
t.Fatalf("parse request package: %v", err)
|
||
|
|
}
|
||
|
|
|
||
|
|
for _, pkg := range packages {
|
||
|
|
for filename, file := range pkg.Files {
|
||
|
|
ast.Inspect(file, func(node ast.Node) bool {
|
||
|
|
field, ok := node.(*ast.Field)
|
||
|
|
if !ok || field.Tag == nil {
|
||
|
|
return true
|
||
|
|
}
|
||
|
|
rawTag, err := strconv.Unquote(field.Tag.Value)
|
||
|
|
if err != nil {
|
||
|
|
t.Errorf("%s: invalid struct tag %s: %v", filename, field.Tag.Value, err)
|
||
|
|
return true
|
||
|
|
}
|
||
|
|
for _, key := range []string{"json", "form", "query", "uri"} {
|
||
|
|
name := strings.Split(reflect.StructTag(rawTag).Get(key), ",")[0]
|
||
|
|
if name == "" || name == "-" {
|
||
|
|
continue
|
||
|
|
}
|
||
|
|
if !isSnakeCaseRequestName(name) {
|
||
|
|
t.Errorf("%s: %s tag %q must use snake_case", filename, key, name)
|
||
|
|
}
|
||
|
|
}
|
||
|
|
return true
|
||
|
|
})
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
func isSnakeCaseRequestName(name string) bool {
|
||
|
|
for _, r := range name {
|
||
|
|
if unicode.IsLower(r) || unicode.IsDigit(r) || r == '_' {
|
||
|
|
continue
|
||
|
|
}
|
||
|
|
return false
|
||
|
|
}
|
||
|
|
return true
|
||
|
|
}
|