代码拉取完成,页面将自动刷新
package captcha
import (
"context"
"gitee.com/neuro-netw0rk/server-golib/errors"
dcaptcha "github.com/dchest/captcha"
"github.com/gin-gonic/gin"
"github.com/go-redis/redis/v7"
)
type Value struct {
ID string `json:"id,omitempty"`
Code string `json:"code,omitempty"`
Img string `json:"img,omitempty"`
Len int `json:"len,omitempty"`
}
type Captcha struct {
enabled bool
options Options
imgExt string
}
type Options struct {
Enabled bool
StoreMode int8
Len int
Width int
Height int
Rds *redis.Client
}
type StoreMode int8
const (
defaultStoreMode = storeModeMem
storeModeMem = 0
storeModeRedis = 1
)
const defaultImgExt = ".png"
const defaultLen = 4
var (
ErrNotEnabled = errors.New("captcha: not enabled")
ErrIDEmpty = errors.New("captcha: id is empty")
)
var C *Captcha
func Init(opts *Options) {
if opts == nil {
return
}
if !opts.Enabled {
return
}
if opts.Rds == nil {
opts.StoreMode = defaultStoreMode
}
if opts.StoreMode != storeModeMem && opts.StoreMode != storeModeRedis {
opts.StoreMode = defaultStoreMode
}
if opts.StoreMode == storeModeRedis {
dcaptcha.SetCustomStore(newRedisMode(context.Background(), opts.Rds))
}
if opts.Width <= 0 {
opts.Width = dcaptcha.StdWidth
}
if opts.Height <= 0 {
opts.Height = dcaptcha.StdHeight
}
if opts.Len <= 0 {
opts.Len = defaultLen
}
C = &Captcha{
enabled: true,
options: *opts,
imgExt: defaultImgExt,
}
}
func (c *Captcha) GetEnabled() bool {
if c == nil {
return false
}
return c.enabled
}
// Get 获取验证码
func (c *Captcha) Get() *Value {
if !c.GetEnabled() {
return &Value{}
}
id := dcaptcha.NewLen(c.options.Len)
return &Value{
ID: id,
Code: "",
Img: id + c.imgExt,
Len: c.options.Len,
}
}
// Verify 验证验证码
func (c *Captcha) Verify(val *Value) bool {
if !c.GetEnabled() {
return true
}
if val == nil {
return false
}
if val.ID == "" || val.Code == "" {
return false
}
return dcaptcha.VerifyString(val.ID, val.Code)
}
// Show 展示验证码
func (c *Captcha) Show(ctx *gin.Context, id string) error {
if !c.GetEnabled() {
return ErrNotEnabled
}
if id == "" {
return ErrIDEmpty
}
err := dcaptcha.WriteImage(ctx.Writer, id, c.options.Width, c.options.Height)
if err != nil {
return err
}
return nil
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。