beego2.x中如何引入验证码模块
beego2.x中如何引入验证码模块呢
Beego框架真的很贴心,默认有captcha这个验证码插件。
https://pkg.go.dev/github.com/beego/beego/v2/server/web/captcha
1、引入captcha对应的两个模块
"github.com/beego/beego/v2/client/cache"
"github.com/beego/beego/v2/server/web/captcha"
2、生成验证码
var cpt *captcha.Captcha
func init() {
store := cache.NewMemoryCache()
cpt = captcha.NewWithFilter("/captcha/", store)
cpt.ChallengeNums = 4
cpt.StdWidth = 100
cpt.StdHeight = 40
}
3、在模板中使用 {{create_captcha}}显示验证码
<form action="/admin/login/doLogin" method="post" id="myform">
<div class="l_title">小米商城后台管理系统-IT营</div>
<dl>
<dd>用户名:<input class="text" type="text" name="username" id="username"></dd>
<dd>密码:<input class="text" type="password" name="password" id="password"></dd>
<dd>验证码:<input id="captcha" type="text" name="captcha">
{{create_captcha}}
</dd>
<dd><input type="submit" class="submit" name="dosubmit" value=""></dd>
</dl>
</form>
4、验证验证码 1、第一种验证方式: {{create_captcha}}这样的方式生成验证码后,它会自动的在我们html上面生成一个隐藏的表单域,所以我们可以通过captchaId来获取表单传过来的 captcha_id
func (c *LoginController) DoLogin() {
captchaId := c.GetString("captchaId")
captchaValue := strings.Trim(c.GetString("captcha"), "")
if !cpt.VerifyReq(captchaId, captchaValue) {
c.Ctx.WriteString("验证码失败")
} else {
c.Ctx.WriteString("验证码成功")
}
}
第二种验证方式:
func (c *LoginController) DoLogin() {
if !cpt.VerifyReq(c.Ctx.Request) {
c.Ctx.WriteString("验证码失败")
} else {
c.Ctx.WriteString("验证码成功")
}
}
5、完整代码 Login控制器
package admin
import (
"strings"
"github.com/astaxie/beego"
"github.com/beego/beego/v2/client/cache"
"github.com/beego/beego/v2/server/web/captcha"
)
var cpt *captcha.Captcha
func init() {
store := cache.NewMemoryCache()
cpt = captcha.NewWithFilter("/captcha/", store)
cpt.ChallengeNums = 4
cpt.StdWidth = 100
cpt.StdHeight = 40
}
type LoginController struct {
beego.Controller
}
func (c *LoginController) Get() {
c.TplName = "admin/login/index.html"
}
func (c *LoginController) DoLogin() {
captchaId := c.GetString("captchaId")
captchaValue := strings.Trim(c.GetString("captcha"), "")
if !cpt.VerifyReq(captchaId, captchaValue) {
c.Ctx.WriteString("验证码失败")
} else {
c.Ctx.WriteString("验证码成功")
}
}
模板文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>用户登录</title>
<link rel="stylesheet" href="/static/css/login.css">
</head>
<body>
<div class="container">
<div id="login">
<form action="/admin/login/doLogin" method="post" id="myform">
<div class="l_title">小米商城后台管理系统-IT营</div>
<dl>
<dd>管理员姓名:<input class="text" type="text" name="username" id="username"></dd>
<dd>管理员密码:<input class="text" type="password" name="password" id="password"></dd>
<dd>验 证 码:<input id="captcha" type="text" name="captcha">
{{create_captcha}}
</dd>
<dd><input type="submit" class="submit" name="dosubmit" value=""></dd>
</dl>
</form>
</div>
</div>
</body>
</html>