验证码中间件

  1. import (
  2. "github.com/lunny/tango"
  3. "github.com/tango-contrib/captcha"
  4. "github.com/tango-contrib/renders"
  5. )
  6. type CaptchaAction struct {
  7. captcha.Captcha
  8. renders.Renderer
  9. }
  10. func (c *CaptchaAction) Get() error {
  11. return c.Render("captcha.html", renders.T{
  12. "captcha": c.CreateHtml(),
  13. })
  14. }
  15. func (c *CaptchaAction) Post() string {
  16. if c.Verify() {
  17. return "true"
  18. }
  19. return "false"
  20. }
  21. func main() {
  22. t := tango.Classic()
  23. t.Use(captcha.New(), renders.New())
  24. t.Any("/", new(CaptchaAction))
  25. t.Run()
  26. }

默认的验证码是保存在内存中,并保留120秒,当然也可以自定义:

  1. package main
  2. import (
  3. "github.com/tango-contrib/cache"
  4. _ "github.com/tango-contrib/cache-redis"
  5. "github.com/tango-contrib/renders"
  6. )
  7. type CaptchaAction struct {
  8. captcha.Captcha
  9. renders.Renderer
  10. }
  11. func (c *CaptchaAction) Get() error {
  12. return c.Render("captcha.html", renders.T{
  13. "captcha": c.CreateHtml(),
  14. })
  15. }
  16. func (c *CaptchaAction) Post() string {
  17. if c.Verify() {
  18. return "true"
  19. }
  20. return "false"
  21. }
  22. func main() {
  23. t := tango.Classic()
  24. c := cache.New(cache.Options{
  25. Adapter: "redis",
  26. AdapterConfig: "addr=:6379,prefix=cache:",
  27. })
  28. t.Use(renders.New(), captcha.New(captcha.Options{Caches: c}))
  29. t.Any("/", new(CaptchaAction))
  30. t.Run()
  31. }

Go的模板如下

  1. package main
  2. import (
  3. "github.com/lunny/tango"
  4. "github.com/tango-contrib/tpongo2"
  5. type CaptchaAction struct {
  6. captcha.Captcha
  7. tpongo2.Renderer
  8. }
  9. func (c *CaptchaAction) Get() error {
  10. return c.Render("captcha_pongo.html", tpongo2.T{
  11. "captcha": c.CreateHtml(),
  12. })
  13. }
  14. func (c *CaptchaAction) Post() string {
  15. if c.Verify() {
  16. return "true"
  17. }
  18. return "false"
  19. }
  20. func main() {
  21. t := tango.Classic()
  22. t.Use(tpongo2.New(), captcha.New())
  23. t.Any("/", new(CaptchaAction))
  24. t.Run()
  25. }

Pongo2的模板如下

选项

  1. // ...
  2. t.Use(captcha.New(captcha.Options{
  3. Caches: cache, // 使用哪种Cache进行验证码数字的存储
  4. URLPrefix: "/captcha/", // URL prefix of getting captcha pictures.
  5. FieldIdName: "captcha_id", // Hidden input element ID.
  6. FieldCaptchaName: "captcha", // User input value element name in request form.
  7. ChallengeNums: 6, // Challenge number.
  8. Width: 240, // Captcha image width.
  9. Height: 80, // Captcha image height.
  10. Expiration: 600, // Captcha expiration time in seconds.
  11. CachePrefix: "captcha_", // Cache key prefix captcha characters.
  12. // ...