-
-
Notifications
You must be signed in to change notification settings - Fork 4.1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add "AllTypes" variable to store all struct types generated by goctl #4647
base: master
Are you sure you want to change the base?
Conversation
Don't get your purpose, would you please describe it in details? |
我需要为所有api开发一个统一的较验入口,现在的做法是为所有的types中的结构添加Validate,这项工作可能遗漏——在一个有几百个API的项目中,我非常需要一个lint工具。 另外,我们的openAPI还有一些规范,例如json属性的取名规范,在提供AllTypes的情况下,便能够使用reflect遍历所有json tag来检查。没有枚举出所有类型的情况下,实现起来非常麻烦。 |
I need to develop a unified verification portal for all APIs, and now the approach is to add Validate to the structure in all types, this work may be missing - in a project with hundreds of APIs, I really need a lint tool. In addition, our openAPI also has some specifications, such as the naming specification of json attributes. When providing AllTypes, we can use reflect to traverse all json tags to check. Without enumeration of all types, it is very troublesome to implement. |
Would you please give me an example on how to use it? |
for example: func CheckTypes(typs []reflect.Type) {
validatorType := reflect.TypeOf((*validation.Validator)(nil)).Elem()
// The Go language CANNOT ENUMERATE all types in a package,
// and static analysis methods such as syntax analysis cannot determine
// whether a certain struct implements a specific interface.
for _, t := range typs {
name := t.Name()
if t.Kind() != reflect.Struct {
log.Fatalf("%s is not a struct", name)
}
// THIS STATEMENT CANNOT BE REPLACED BY ANY STATIC ANALYSIS.
if !reflect.PtrTo(t).Implements(validatorType) {
log.Fatalf("Struct %s does not implement 'Validator' interface")
}
// checking json field name(goZero style)
checkFieldJsonNaming(t)
// check validate tag(using go-playground/validator)
checkFieldValidateTag(t)
// other check for restful api request/response type
...
}
} |
为生成的types.go文件添加一个AllTypes []reflect.Type,这样主框架可以枚举到所有生成的类型,这让统一检查这些类型成为可能(例如lint工具,静态检查有时不好使:规范上要求实现Validate来较验数据,tag上标注好但代码上遗漏了)