package models import ( "fmt" "main/configs" "math/rand" "time" ) type Code struct { Email string `json:"email"` Mobile string `json:"mobile"` Code string `json:"code"` Expire time.Time `json:"expire"` } func init() { configs.ORMDB().AutoMigrate(&Code{}) } func CodeCreate(email, mobile string) (err error) { code := fmt.Sprintf("%06v", rand.New(rand.NewSource(time.Now().UnixNano())).Int31n(1000000)) // 如果是邮箱,发送邮件 if email != "" { go func() { // 发送邮件 // ... }() } // 如果是手机,发送短信 if mobile != "" { go func() { // 发送短信 // ... }() } // 保存验证码 configs.ORMDB().Create(&Code{ Email: email, Mobile: mobile, Code: code, Expire: time.Now().Add(time.Minute * 5), }) return nil } func EmailCheck(email, code string) (err error) { var data Code configs.ORMDB().Where("email = ?", email).First(&data) if data.Code == code && data.Expire.After(time.Now()) { return nil } return fmt.Errorf("验证码错误") } func MobileCheck(mobile, code string) (err error) { var data Code configs.ORMDB().Where("mobile = ?", mobile).First(&data) if data.Code == code && data.Expire.After(time.Now()) { return nil } return fmt.Errorf("验证码错误") }