1 Star 0 Fork 0

Cruvie Kang/kk_go_kit

加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
bind_check_gen.go 2.10 KB
一键复制 编辑 原始数据 按行查看 历史
cruvie 提交于 2024-11-02 22:23 +08:00 . gen ts
package kk_api_gen
import (
"fmt"
"gitee.com/cruvie/kk_go_kit/kk_file"
"gitee.com/cruvie/kk_go_kit/kk_log"
"log/slog"
"reflect"
)
func BindCheckGen(s ...any) {
str := ""
for _, a := range s {
str += gen(a)
}
err := kk_file.AppendOrCreateFile("new_api/bind_check.go", []byte(str))
if err != nil {
slog.Error("gen bind_check.go error", kk_log.NewLog(nil).Error(err).Args()...)
}
}
func gen(s any) string {
// 获取p的反射类型对象
t := reflect.TypeOf(s)
str := fmt.Sprintf(`
func (x *%s) BindCheck(stage *kk_stage.Stage) error {
err := kk_http.ReadProtoBuf(stage, x)
if err != nil {
return err
}
%s
return nil
}
`, t.Name(), genCheckCode(s))
return str
}
// genCheckCode 检查结构体s的所有导出字段是否为其类型的默认值
func genCheckCode(s any) string {
val := reflect.ValueOf(s)
if val.Kind() == reflect.Ptr {
val = val.Elem() // 如果传入的是指针,解引用
}
// 确保传入的是结构体
if val.Kind() != reflect.Struct {
fmt.Println("Error: not a struct")
return ""
}
str := ""
// 遍历结构体的所有字段
for i := range val.NumField() {
valueField := val.Field(i)
typeField := val.Type().Field(i)
// 检查字段是否导出(首字母大写)
if typeField.PkgPath == "" { // 空的PkgPath表示字段是导出的
str += judgingZeroCode(valueField, typeField)
}
}
return str
}
func judgingZeroCode(v reflect.Value, typeField reflect.StructField) string {
switch v.Kind() {
case reflect.Slice:
return fmt.Sprintf(`
if len(x.Get%s()) == 0 {
return errors.New("%s is empty")
}
`, typeField.Name, typeField.Name)
case reflect.String:
return fmt.Sprintf(`
if x.Get%s() == "" {
return errors.New("%s is empty")
}
`, typeField.Name, typeField.Name)
case reflect.Uint64:
return fmt.Sprintf(`
if !kk_id.CheckIdValid(x.Get%s()) {
return errors.New("%s is invalid")
}
`, typeField.Name, typeField.Name)
case reflect.Uint32, reflect.Int32, reflect.Int64:
return fmt.Sprintf(`
if x.Get%s() == 0 {
return errors.New("%s is invalid")
}
`, typeField.Name, typeField.Name)
default:
return `unknown type` + typeField.Name
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/cruvie/kk_go_kit.git
git@gitee.com:cruvie/kk_go_kit.git
cruvie
kk_go_kit
kk_go_kit
v0.1.2

搜索帮助