name: 验证码

sort: 1

验证码

验证码分成两部分:一个是展示验证码的页面;一个是验证验证码。

于是我们可以先定义两个接口:

  1. package controllers
  2. import (
  3. web "github.com/beego/beego/v2/server/web"
  4. "github.com/beego/beego/v2/client/cache"
  5. "github.com/beego/beego/v2/server/web/captcha"
  6. )
  7. var cpt *captcha.Captcha
  8. func init() {
  9. // use beego cache system store the captcha data
  10. store := cache.NewMemoryCache()
  11. cpt = captcha.NewWithFilter("/captcha/", store)
  12. }
  13. type MainController struct {
  14. web.Controller
  15. }
  16. func (this *MainController) Get() {
  17. this.TplName = "index.tpl"
  18. }
  19. func (this *MainController) Post() {
  20. this.TplName = "index.tpl"
  21. this.Data["Success"] = cpt.VerifyReq(this.Ctx.Request)
  22. }

前端页面可以很简单:

  1. {{.Success}}
  2. <form action="/" method="post">
  3. {{create_captcha}}
  4. <input name="captcha" type="text">
  5. </form>