4 ZH_Captcha
Lunny Xiao edited this page 2019-11-27 09:08:08 +08:00
This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

验证码中间件

Captcha中间件提供了验证码服务他是一个 Tango 的插件。

安装

go get gitea.com/tango/captcha

示例

package main

import (
	"gitea.com/lunny/tango"
	"gitea.com/tango/captcha"
	"gitea.com/tango/renders"
)

type CaptchaAction struct {
	captcha.Captcha
	renders.Renderer
}

func (c *CaptchaAction) Get() error {
	return c.Render("captcha.html", renders.T{
		"captcha": c.CreateHtml(),
	})
}

func (c *CaptchaAction) Post() string {
	if c.Verify() {
		return "true"
	}
	return "false"
}

func main() {
	t := tango.Classic()
	t.Use(captcha.New(), renders.New())
	t.Any("/", new(CaptchaAction))
	t.Run()
}

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

package main

import (
	"gitea.com/lunny/tango"
	"gitea.com/tango/cache"
	"gitea.com/tango/captcha"
	"gitea.com/tango/renders"
)

type CaptchaAction struct {
	captcha.Captcha
	renders.Renderer
}

func (c *CaptchaAction) Get() error {
	return c.Render("captcha.html", renders.T{
		"captcha": c.CreateHtml(),
	})
}

func (c *CaptchaAction) Post() string {
	if c.Verify() {
		return "true"
	}
	return "false"
}

func main() {
  	t := tango.Classic()
	c := cache.New(cache.Options{
		Adapter: "memory",
		Interval: 120,
	})
	t.Use(renders.New(), captcha.New(captcha.Options{Caches: c}))
	t.Any("/", new(CaptchaAction))
	t.Run()
}

如果希望使用Redis或者其他来保存也可以

package main

import (
	"gitea.com/lunny/tango"
	"gitea.com/tango/cache"
	_ "gitea.com/tango/cache-redis"
	"gitea.com/tango/captcha"
	"gitea.com/tango/renders"
)

type CaptchaAction struct {
	captcha.Captcha
	renders.Renderer
}

func (c *CaptchaAction) Get() error {
	return c.Render("captcha.html", renders.T{
		"captcha": c.CreateHtml(),
	})
}

func (c *CaptchaAction) Post() string {
	if c.Verify() {
		return "true"
	}
	return "false"
}

func main() {
	t := tango.Classic()
	c := cache.New(cache.Options{
		Adapter:       "redis",
		AdapterConfig: "addr=:6379,prefix=cache:",
	})
	t.Use(renders.New(), captcha.New(captcha.Options{Caches: c}))
	t.Any("/", new(CaptchaAction))
	t.Run()
}
<!-- templates/captcha.tmpl -->
{{.captcha}}

选项

captcha.Options 有很多可以选择的配置,当然这些配置都有缺省值:

// ...
t.Use(captcha.New(captcha.Options{
	Caches: cache,
	URLPrefix:			"/captcha/", 	// URL prefix of getting captcha pictures.
	FieldIdName:		"captcha_id", 	// Hidden input element ID.
	FieldCaptchaName:	"captcha", 		// User input value element name in request form.
	ChallengeNums:		6, 				// Challenge number.
	Width:				240,			// Captcha image width.
	Height:				80,				// Captcha image height.
	Expiration:			600, 			// Captcha expiration time in seconds.
	CachePrefix:		"captcha_", 	// Cache key prefix captcha characters.
}))
// ...