温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Go怎么整合captcha实现验证码功能

发布时间:2023-03-01 14:01:00 来源:亿速云 阅读:83 作者:iii 栏目:开发技术

这篇“Go怎么整合captcha实现验证码功能”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“Go怎么整合captcha实现验证码功能”文章吧。

1 captcha概述

captcha的使用设计流程

Go怎么整合captcha实现验证码功能

2 实现代码(使用内存缓存)

2.1 后端代码

生成验证码图片API:

//GenerateImg 生成验证码图片名称
func GenerateImg(w http.ResponseWriter, req *http.Request) {
   w.Header().Set("Access-Control-Allow-Origin", "*")             //允许访问所有域
   w.Header().Add("Access-Control-Allow-Headers", "Content-Type") 
   d := struct {
      CaptchaId string
   }{
      captcha.New(),
   }
   bytes, _ := json.Marshal(map[string]interface{}{"code": 0, "msg": "", "count": 0, "data": d.CaptchaId})
   w.Write(bytes)
}

HTTP服务:

func RunHttp(port string) {
   logger := log.Default()

   http.Header{}.Set("Access-Control-Allow-Origin", "*")

   http.HandleFunc("/user/login", controller.UserLogin) //登录API
   http.HandleFunc("/img", controller.GenerateImg)  //生成验证码图片API
   http.Handle("/verify/", captcha.Server(captcha.StdWidth, captcha.StdHeight)) //刷新验证码API

   logger.Println("Http Server Running port:", port, "...")
   http.ListenAndServe(":"+port, nil)
}

启动HTTP服务:

func main() {
   web.RunHttp("8000")
}

验证码验证:

//UserLogin 用户登录
func UserLogin(w http.ResponseWriter, req *http.Request) {
   w.Header().Set("Access-Control-Allow-Origin", "*")
   w.Header().Add("Access-Control-Allow-Headers", "Content-Type")
   ......
   var m map[string]string
   body, err := ioutil.ReadAll(req.Body)
   if err != nil {
      panic(err)
   }
   json.Unmarshal(body, &m)
   var k = m["verify_key"]
   var v = m["verify_value"]
   res := captcha.VerifyString(k, v)
   if res { // 验证通过
     ......
   } else { // 验证未通过
     ......
   }
   ......
}

2.2 前端代码

......

<form class="layui-form" id="form">
    <h4 >登录</h4>
    <div class="layui-form-item">
        <label class="layui-form-label">账号</label>
        <div class="layui-input-inline">
            <input type="text" id="loginName" placeholder="请输入账号" autocomplete="off"
                   class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">密码</label>
        <div class="layui-input-inline">
            <input type="password" id="loginPwd" placeholder="请输入密码" autocomplete="off"
                   class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">验证码</label>
        <div class="layui-input-inline">
            <input type="text" id="loginV" placeholder="请输入验证码" autocomplete="off"
                   class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <div class="layui-input-block">
            <button class="layui-btn" type="button" onclick="login()">立即提交</button>
            <button type="button" onclick="toRegister()" class="layui-btn layui-btn-primary">注册</button>
        </div>
    </div>
</form>
<img id="verify" onclick="reload()"></img>
......
<input type="hidden" id="verify_key">
</body>
<script src="//unpkg.com/layui@2.6.8/dist/layui.js"></script>
<script src="//cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
<script>
    const base_url = 'http://localhost:8000'

    init()

    function init() {
        $.ajax({
            url: base_url + "/img",
            type: "GET",
            success: function (res) {
                var obj = JSON.parse(res)
                $("#verify").attr("src", base_url + "/verify/" + obj.data + ".png")
                $("#verify_key").attr("value", obj.data)
            }
        })
    }

    function reload() {
        var url = $("#verify").attr("src");
        $("#verify").attr("src", url + "?reload=" + (new Date()).getTime())
    }

    function login() {
        var loginName = $("#loginName").val()
        var loginPwd = $("#loginPwd").val()
        var verify_key = $("#verify_key").val()
        var loginV = $("#loginV").val()
        var data = {
            'login_name': loginName,
            'pwd': loginPwd,
            'verify_key': verify_key,
            'verify_value': loginV
        }
        $.ajax({
            url: base_url + "/user/login",
            type: "POST",
            data: JSON.stringify(data),
            success: function (res) {
               ......
            },
            ......
        })
    }

   ......
   
</script>

2.3 注意点

跨域问题:可加入如下代码

w.Header().Set("Access-Control-Allow-Origin", "*")             //允许访问所有域
w.Header().Add("Access-Control-Allow-Headers", "Content-Type")

3 自定义Store(使用Redis缓存)

3.1 自定义对象并实现Store抽象

Redis初始化:

var (
   RDB          *redis.Client
   TokenTimeOut = time.Second * 3600
)

func init() {
   RDB = redis.NewClient(&redis.Options{
      Addr:     "127.0.0.1:6379",
      Password: "",
      DB:       0,
   })
}

自定义结构体&实现Store抽象:

type StoreImpl struct {
   RDB        *redis.Client
   Expiration time.Duration
}

func (impl *StoreImpl) Set(id string, digits []byte) {
   impl.RDB.Set(context.Background(), id, string(digits), impl.Expiration)
}

func (impl *StoreImpl) Get(id string, clear bool) (digits []byte) {
   bytes, _ := impl.RDB.Get(context.Background(), id).Bytes()
   return bytes
}

3.2 配置captcha,加入自定义Store实现

//GenerateImg 生成验证码图片名称
func GenerateImg(w http.ResponseWriter, req *http.Request) {
   w.Header().Set("Access-Control-Allow-Origin", "*")             //允许访问所有域
   w.Header().Add("Access-Control-Allow-Headers", "Content-Type") //header的类型
   //需要在New之前进行指定
   captcha.SetCustomStore(&verify.StoreImpl{
      RDB:        dao.RDB,
      Expiration: time.Second * 1000,
   })
   d := struct {
      CaptchaId string
   }{
      captcha.New(),
   }
   bytes, _ := json.Marshal(map[string]interface{}{"code": 0, "msg": "", "count": 0, "data": d.CaptchaId})
   w.Write(bytes)
}

3.3 注意点

  • 需要在captcha.New()之前进行captcha.SetCustomStore()

  • 在captcha.SetCustomStore()之后,自定义的方法实现Store接口时需要完整实现,也就是能真正的实现存储或缓存功能,否则验证码无法生成

以上就是关于“Go怎么整合captcha实现验证码功能”这篇文章的内容,相信大家都有了一定的了解,希望小编分享的内容对大家有帮助,若想了解更多相关的知识内容,请关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI