程序开发中经常遇到一些需要登录验证的场合,这里简要介绍一下基于beego框架的邮箱随机码验证
先定义一个Map存放邮箱号及对应随机码
var captchaMap map[string]string
func Initialize() {
captchaMap = make(map[string]string)
}
在models中定义返回结构,其中code 含义 1 成功 0 失败
type GeneralResp struct {
Code int `json:"code"`
Data interface{} `json:"data"`
Error string `json:"error"`
}
一、邮箱验证
func (this *MainController) AddressVerify() {
userAddress := this.Input().Get("userAddress")
if userAddress != tools.CheckAddress(userAddress) { // 邮箱验证,验证邮箱是否存在
this.Data["json"] = models.GeneralResp{Code: 0,Error:"userAddress is not right!"}
} else {
captchaValue := tools.CreateCaptcha() //生成随机验证码
captchaMap[userAddress] = captchaValue
err := sendMessage(models.SmtpRecv{To: []string{userAddress}, Body: captchaValue}) // 向验证邮箱发送验证码
if err != nil {
this.Data["json"] = models.GeneralResp{Code: 0, Error: err.Error()}
} else {
this.Data["json"] = models.GeneralResp{Code: 1}
}
}
this.ServeJSON()
}
二、邮箱随机码验证
func (this *MainController) CaptchaVerify() {
userAddress := this.Input().Get("userAddress")
captchaValue := captchaMap[userAddress]
if !strings.EqualFold(captchaValue, this.Input().Get("captcha")) {
this.Data["json"] = models.GeneralResp{Code: 0}
} else {
delete(captchaMap, userAddress)
this.Data["json"] = models.GeneralResp{Code: 1}
}
this.ServeJSON()
}
如有不对欢迎指正,相互学习,共同进步。