1,验证码库的地址
GitHub - mojocn/base64Captcha: captcha of base64 image string
2,安装验证码库:
liuhongdi@ku:~$ go get -u github.com/mojocn/base64Captcha
3,redis库的地址:
https://github.com/go-redis/redis
4,安装redis库:
liuhongdi@ku:~$ go get -u github.com/go-redis/redis/v8
说明:刘宏缔的go森林是一个专注golang的博客,
网站:https://blog.imgtouch.com
原文: go语言web开发系列之十九:gin框架:go-redis v8+base64Captcha v1.3.1实现用redis存储图形验证码 – 架构森林
说明:作者:刘宏缔 邮箱: [email protected]
1,地址:
GitHub - liuhongdi/digv19: gin框架:go-redis+base64Captcha实现用redis存储图形验证码
2,功能说明:演示了用base64Captcha库生成图形验证码
3,项目结构:如图:
1,global/setting.go
package global
import (
"github.com/liuhongdi/digv19/pkg/setting"
"time"
)
//服务器配置
type ServerSettingS struct {
RunMode string
HttpPort string
ReadTimeout time.Duration
WriteTimeout time.Duration
}
//redis配置
type RedisSettingS struct {
Addr string
Password string
}
//静态目录配置
type StaticSettingS struct {
StaticDir string //静态文件目录
}
//定义全局变量
var (
ServerSetting *ServerSettingS
StaticSetting *StaticSettingS
RedisSetting *RedisSettingS
)
//读取配置到全局变量
func SetupSetting() error {
s, err := setting.NewSetting()
if err != nil {
return err
}
err = s.ReadSection("Server", &ServerSetting)
if err != nil {
return err
}
err = s.ReadSection("Static", &StaticSetting)
if err != nil {
return err
}
err = s.ReadSection("Redis", &RedisSetting)
if err != nil {
return err
}
return nil
}
2,global/redisDb.go
package global
import (
"context"
"github.com/go-redis/redis/v8"
)
var (
RedisDb *redis.Client
)
//创建redis链接
func SetupRedisDb() (error) {
var ctx = context.Background()
RedisDb = redis.NewClient(&redis.Options{
Addr: RedisSetting.Addr,
Password: RedisSetting.Password, // no password set
DB: 0, // use default DB
})
_, err := RedisDb.Ping(ctx).Result()
if err != nil {
return err
}
return nil
}
3,cache/redisStore.go
package cache
import (
"context"
"fmt"
"github.com/liuhongdi/digv19/global"
"log"
"time"
)
var ctx = context.Background()
const CAPTCHA = "captcha:"
type RedisStore struct {
}
//set a capt
func (r RedisStore) Set(id string, value string) {
key := CAPTCHA + id
err := global.RedisDb.Set(ctx,key, value, time.Minute*2).Err()
if err != nil {
log.Println(err.Error())
}
}
//get a capt
func (r RedisStore) Get(id string, clear bool) string {
key := CAPTCHA + id
val, err := global.RedisDb.Get(ctx, key).Result()
if err != nil {
fmt.Println(err)
return ""
}
if clear {
err := global.RedisDb.Del(ctx,key).Err()
if err != nil {
fmt.Println(err)
return ""
}
}
return val
}
//verify a capt
func (r RedisStore) Verify(id, answer string, clear bool) bool {
v := RedisStore{}.Get(id, clear)
//fmt.Println("key:"+id+";value:"+v+";answer:"+answer)
return v == answer
}
4,service/capt.go
package service
import (
"github.com/liuhongdi/digv19/cache"
"github.com/mojocn/base64Captcha"
"image/color"
)
// 设置自带的store
//var store = base64Captcha.DefaultMemStore
//使用redis作为store
var store = cache.RedisStore{}
//生成验证码
func CaptMake() (id, b64s string, err error) {
var driver base64Captcha.Driver
var driverString base64Captcha.DriverString
// 配置验证码信息
captchaConfig := base64Captcha.DriverString{
Height: 60,
Width: 200,
NoiseCount: 0,
ShowLineOptions: 2 | 4,
Length: 4,
Source: "1234567890qwertyuioplkjhgfdsazxcvbnm",
BgColor: &color.RGBA{
R: 3,
G: 102,
B: 214,
A: 125,
},
Fonts: []string{"wqy-microhei.ttc"},
}
driverString = captchaConfig
driver = driverString.ConvertFonts()
captcha := base64Captcha.NewCaptcha(driver, store)
lid, lb64s, lerr := captcha.Generate()
return lid, lb64s, lerr
}
//验证captcha是否正确
func CaptVerify(id string,capt string) bool {
if store.Verify(id, capt, false) {
return true
} else {
return false
}
}
5,controller/idController.go
package controller
import (
"github.com/gin-gonic/gin"
"github.com/liuhongdi/digv19/pkg/result"
"github.com/liuhongdi/digv19/service"
)
type IdController struct{}
func NewIdController() IdController {
return IdController{}
}
//存储验证码的结构
type CaptchaResult struct {
Id string `json:"id"`
Base64Blob string `json:"base_64_blob"`
//VerifyValue string `json:"code"`
}
// 生成图形化验证码
func (a *IdController) GetOne(ctx *gin.Context) {
resultRes := result.NewResult(ctx)
id, b64s, err := service.CaptMake()
if err != nil {
resultRes.Error(1,err.Error())
}
captchaResult := CaptchaResult{
Id: id,
Base64Blob: b64s,
}
resultRes.Success(captchaResult)
return
}
//验证captcha是否正确
func (a *IdController) Verify(c *gin.Context) {
id := c.PostForm("id")
capt := c.PostForm("capt")
resultRes := result.NewResult(c)
if (id == "" || capt == "") {
resultRes.Error(400,"param error")
}
if service.CaptVerify(id, capt) == true {
resultRes.Success("success")
} else {
resultRes.Error(1,"verify failed")
}
return
}
6,其他相关代码可访问github查看
1,访问:
http://127.0.0.1:8000/static/getcapt.html
返回:
2,查看redis中的记录:
liuhongdi@ku:~$ /usr/local/soft/redis6/bin/redis-cli
127.0.0.1:6379> keys *
1) "captcha:H2bnkF7CS9NSNCS8VeMn"
2) "id_logId"
3) "article_3"
4) "article_2"
127.0.0.1:6379> get captcha:H2bnkF7CS9NSNCS8VeMn
"g3m0"
可以看到和图片上显示的内容一致
3,测试错误
4,测试正确输入:
module github.com/liuhongdi/digv19
go 1.15
require (
github.com/gin-gonic/gin v1.6.3
github.com/go-playground/universal-translator v0.17.0
github.com/go-playground/validator/v10 v10.2.0
github.com/go-redis/redis/v8 v8.3.3
github.com/mojocn/base64Captcha v1.3.1
github.com/magiconair/properties v1.8.4 // indirect
github.com/mitchellh/mapstructure v1.3.3 // indirect
github.com/pelletier/go-toml v1.8.1 // indirect
github.com/spf13/afero v1.4.1 // indirect
github.com/spf13/cast v1.3.1 // indirect
github.com/spf13/jwalterweatherman v1.1.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/spf13/viper v1.7.1
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68 // indirect
golang.org/x/text v0.3.4 // indirect
gopkg.in/ini.v1 v1.62.0 // indirect
gopkg.in/yaml.v2 v2.3.0 // indirect
)