package main
import (
"context"
"fmt"
"github.com/gogf/gf/v2/database/gdb"
"github.com/gogf/gf/v2/errors/gerror"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gctx"
"github.com/gogf/gf/v2/util/gvalid"
"time"
)
type UserCreateReq struct {
g.Meta `v:"UserCreateReq"`
Name string
Pass string
}
func RuleUserCreateReq(ctx context.Context, in gvalid.RuleFuncInput) error {
var req *UserCreateReq
if err := in.Data.Scan(&req); err != nil {
return gerror.Wrap(err, `Scan data to UserCreateReq failed`)
}
// SELECT COUNT(*) FROM `user` WHERE `name` = xxx
count, err := g.Model("user").Ctx(ctx).Cache(gdb.CacheOption{
Duration: time.Hour,
Name: "",
Force: false,
}).Where("name", req.Name).Count()
if err != nil {
return err
}
if count > 0 {
return gerror.Newf(`The name "%s" is already token by others`, req.Name)
}
return nil
}
func main() {
var (
ctx = gctx.New()
user = &UserCreateReq{
Name: "john",
Pass: "123456",
}
)
err := g.Validator().RuleFunc("UserCreateReq", RuleUserCreateReq).Data(user).Run(ctx)
fmt.Println(err)
}