• go语言web开发系列之十八:gin框架用base64Captcha生成图形验证码


    一,安装库

    1,库的地址

    https://github.com/mojocn/base64Captcha

    2,安装:

    liuhongdi@ku:~$ go get -u github.com/mojocn/base64Captcha

    说明:刘宏缔的go森林是一个专注golang的博客,
              地址:https://blog.csdn.net/weixin_43881017

    说明:作者:刘宏缔 邮箱: 371125307@qq.com

    二,演示项目的相关信息

    1,地址:

    https://github.com/liuhongdi/digv18

    2,功能说明:演示了用base64Captcha库生成图形验证码

    3,项目结构:如图:

    三,go代码说明

    1,service/capt.go

    1.  
      package service
    2.  
       
    3.  
      import (
    4.  
      "fmt"
    5.  
      "image/color"
    6.  
      "github.com/mojocn/base64Captcha"
    7.  
      )
    8.  
       
    9.  
      // 设置自带的store
    10.  
      var store = base64Captcha.DefaultMemStore
    11.  
       
    12.  
      //生成验证码
    13.  
      func CaptMake() (id, b64s string, err error) {
    14.  
      var driver base64Captcha.Driver
    15.  
      var driverString base64Captcha.DriverString
    16.  
       
    17.  
      // 配置验证码信息
    18.  
      captchaConfig := base64Captcha.DriverString{
    19.  
      Height: 60,
    20.  
      Width: 200,
    21.  
      NoiseCount: 0,
    22.  
      ShowLineOptions: 2 | 4,
    23.  
      Length: 4,
    24.  
      Source: "1234567890qwertyuioplkjhgfdsazxcvbnm",
    25.  
      BgColor: &color.RGBA{
    26.  
      R: 3,
    27.  
      G: 102,
    28.  
      B: 214,
    29.  
      A: 125,
    30.  
      },
    31.  
      Fonts: []string{"wqy-microhei.ttc"},
    32.  
      }
    33.  
       
    34.  
      driverString = captchaConfig
    35.  
      driver = driverString.ConvertFonts()
    36.  
      captcha := base64Captcha.NewCaptcha(driver, store)
    37.  
      lid, lb64s, lerr := captcha.Generate()
    38.  
      return lid, lb64s, lerr
    39.  
      }
    40.  
       
    41.  
      //验证captcha是否正确
    42.  
      func CaptVerify(id string,capt string) bool {
    43.  
      fmt.Println("id:"+id)
    44.  
      fmt.Println("capt:"+capt)
    45.  
      //if store.Verify(id, capt, true) {
    46.  
      if store.Verify(id, capt, false) {
    47.  
      return true
    48.  
      } else {
    49.  
      return false
    50.  
      }
    51.  
      //return
    52.  
      }

    2,controller/idController.go

    1.  
      package controller
    2.  
       
    3.  
      import (
    4.  
      "github.com/gin-gonic/gin"
    5.  
      "github.com/liuhongdi/digv18/pkg/result"
    6.  
      "github.com/liuhongdi/digv18/service"
    7.  
      //"github.com/liuhongdi/digv18/service"
    8.  
      )
    9.  
       
    10.  
      type IdController struct{}
    11.  
       
    12.  
      func NewIdController() IdController {
    13.  
      return IdController{}
    14.  
      }
    15.  
       
    16.  
      //存储验证码的结构
    17.  
      type CaptchaResult struct {
    18.  
      Id string `json:"id"`
    19.  
      Base64Blob string `json:"base_64_blob"`
    20.  
      //VerifyValue string `json:"code"`
    21.  
      }
    22.  
       
    23.  
      // 生成图形化验证码
    24.  
      func (a *IdController) GetOne(ctx *gin.Context) {
    25.  
      resultRes := result.NewResult(ctx)
    26.  
      id, b64s, err := service.CaptMake()
    27.  
      if err != nil {
    28.  
      resultRes.Error(1,err.Error())
    29.  
      }
    30.  
      captchaResult := CaptchaResult{
    31.  
      Id: id,
    32.  
      Base64Blob: b64s,
    33.  
      }
    34.  
      resultRes.Success(captchaResult)
    35.  
      return
    36.  
      }
    37.  
       
    38.  
      //验证captcha是否正确
    39.  
      func (a *IdController) Verify(c *gin.Context) {
    40.  
       
    41.  
      id := c.PostForm("id")
    42.  
      capt := c.PostForm("capt")
    43.  
      resultRes := result.NewResult(c)
    44.  
      if (id == "" || capt == "") {
    45.  
      resultRes.Error(400,"param error")
    46.  
      }
    47.  
       
    48.  
      if service.CaptVerify(id, capt) == true {
    49.  
      resultRes.Success("success")
    50.  
      } else {
    51.  
      resultRes.Error(1,"verify failed")
    52.  
      }
    53.  
      return
    54.  
      }

    3,router/router.go

    1.  
      package router
    2.  
       
    3.  
      import (
    4.  
      "github.com/gin-gonic/gin"
    5.  
      "github.com/liuhongdi/digv18/controller"
    6.  
      "github.com/liuhongdi/digv18/global"
    7.  
      "github.com/liuhongdi/digv18/pkg/result"
    8.  
      "log"
    9.  
      "net/http"
    10.  
      "runtime/debug"
    11.  
      )
    12.  
       
    13.  
      func Router() *gin.Engine {
    14.  
      router := gin.Default()
    15.  
      //处理异常
    16.  
      router.NoRoute(HandleNotFound)
    17.  
      router.NoMethod(HandleNotFound)
    18.  
      router.Use(Recover)
    19.  
       
    20.  
      //static
    21.  
      router.StaticFS("/static", http.Dir(global.StaticSetting.StaticDir))
    22.  
       
    23.  
      // 路径映射
    24.  
      idc:=controller.NewIdController()
    25.  
      router.GET("/id/getone", idc.GetOne);
    26.  
      router.POST("/id/verify", idc.Verify);
    27.  
      return router
    28.  
      }
    29.  
       
    30.  
      //404
    31.  
      func HandleNotFound(c *gin.Context) {
    32.  
      result.NewResult(c).Error(404,"资源未找到")
    33.  
      return
    34.  
      }
    35.  
       
    36.  
      //500
    37.  
      func Recover(c *gin.Context) {
    38.  
      defer func() {
    39.  
      if r := recover(); r != nil {
    40.  
      //打印错误堆栈信息
    41.  
      log.Printf("panic: %v ", r)
    42.  
      debug.PrintStack()
    43.  
      result.NewResult(c).Error(500,"服务器内部错误")
    44.  
      }
    45.  
      }()
    46.  
      //继续后续接口调用
    47.  
      c.Next()
    48.  
      }

    4,static/getcapt.html

    1.  
      <!DOCTYPE html>
    2.  
      <html lang="en">
    3.  
      <head>
    4.  
      <meta charset="UTF-8">
    5.  
      <title>Title</title>
    6.  
      <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
    7.  
      </head>
    8.  
      <body>
    9.  
      <img id="capt" src="" /><br/>
    10.  
      <input id="captvalue" placeholder="请输入验证码" /><br/>
    11.  
      <input type="button" name="save" value="提交" onclick="submit()" />
    12.  
      <script>
    13.  
       
    14.  
      var curCaptId = "";
    15.  
      //得到图形验证码和id
    16.  
      $.ajax({
    17.  
      type: "GET",
    18.  
      url: "/id/getone",
    19.  
      data: {},
    20.  
      dataType: "JSON",
    21.  
      success: function(result) {
    22.  
      curCaptId = result.data.id;
    23.  
      document.getElementById("capt").src=result.data.base_64_blob;
    24.  
      }
    25.  
      });
    26.  
       
    27.  
      //提交验证码和id
    28.  
      function submit() {
    29.  
      var capt = document.getElementById("captvalue").value;
    30.  
      var postdata = {
    31.  
      "id":curCaptId,
    32.  
      "capt":capt
    33.  
      };
    34.  
      $.ajax({
    35.  
      type: "POST",
    36.  
      url: "/id/verify",
    37.  
      data: postdata,
    38.  
      dataType: "JSON",
    39.  
      success: function(result) {
    40.  
      if (result.code == 0){
    41.  
      alert("验证成功");
    42.  
      } else {
    43.  
      alert("验证错误:"+result.msg);
    44.  
      }
    45.  
      }
    46.  
      });
    47.  
      }
    48.  
       
    49.  
      </script>
    50.  
      </body>
    51.  
      </html>

    5,其他相关代码可访问github查看

    四,效果测试

    1,访问:

    http://127.0.0.1:8000/static/getcapt.html

    返回:

    2,测试错误返回:

    3,测试正确返回:

    五,查看库的版本:

    1.  
      module github.com/liuhongdi/digv18
    2.  
       
    3.  
      go 1.15
    4.  
       
    5.  
      require (
    6.  
      github.com/gin-gonic/gin v1.6.3
    7.  
      github.com/go-playground/universal-translator v0.17.0
    8.  
      github.com/go-playground/validator/v10 v10.2.0
    9.  
      github.com/mojocn/base64Captcha v1.3.1
    10.  
      github.com/magiconair/properties v1.8.4 // indirect
    11.  
      github.com/mitchellh/mapstructure v1.3.3 // indirect
    12.  
      github.com/pelletier/go-toml v1.8.1 // indirect
    13.  
      github.com/spf13/afero v1.4.1 // indirect
    14.  
      github.com/spf13/cast v1.3.1 // indirect
    15.  
      github.com/spf13/jwalterweatherman v1.1.0 // indirect
    16.  
      github.com/spf13/pflag v1.0.5 // indirect
    17.  
      github.com/spf13/viper v1.7.1
    18.  
      golang.org/x/sys v0.0.0-20201119102817-f84b799fce68 // indirect
    19.  
      golang.org/x/text v0.3.4 // indirect
    20.  
      gopkg.in/ini.v1 v1.62.0 // indirect
    21.  
      gopkg.in/yaml.v2 v2.3.0 // indirect
    22.  
      )
  • 相关阅读:
    在腾讯云上使用URLOS一键安装Discuz! Q
    共享容器——URLOS最新发布的一项超强功能
    在群晖NAS上运行URLOS之后竟然能安装Discuz! Q!!
    Discuz!Q回归,如何一键安装Discuz!Q
    Docker管理面板-URLOS(易用、高效、强大)
    CentOS下Subversion(SVN)的快速安装与配置
    通过URLOS安装Redis缓存为wordpress网站提速
    5分钟快速安装Redmine项目管理软件
    Python3+HTMLTestRunner+SMTP生成测试报告后发送邮件
    Python3+HTMLTestRunner生成html测试报告时报错HTMLTestRunner.py line 687, in generateReport  self.stream.write(output.encode('utf8'))
  • 原文地址:https://www.cnblogs.com/ExMan/p/14312296.html
Copyright © 2020-2023  润新知