这篇“Go怎么整合captcha实现验证码功能”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“Go怎么整合captcha实现验
这篇“Go怎么整合captcha实现验证码功能”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“Go怎么整合captcha实现验证码功能”文章吧。
captcha的使用设计流程
生成验证码图片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 { // 验证未通过 ...... } ......}
......<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>
跨域问题:可加入如下代码
w.Header().Set("Access-Control-Allow-Origin", "*") //允许访问所有域w.Header().Add("Access-Control-Allow-Headers", "Content-Type")
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}
//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)}
需要在captcha.New()之前进行captcha.SetCustomStore()
在captcha.SetCustomStore()之后,自定义的方法实现Store接口时需要完整实现,也就是能真正的实现存储或缓存功能,否则验证码无法生成
以上就是关于“Go怎么整合captcha实现验证码功能”这篇文章的内容,相信大家都有了一定的了解,希望小编分享的内容对大家有帮助,若想了解更多相关的知识内容,请关注编程网精选频道。
--结束END--
本文标题: Go怎么整合captcha实现验证码功能
本文链接: https://www.lsjlt.com/news/350422.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-05-03
2024-05-03
2024-05-03
2024-05-03
2024-05-03
2024-05-03
2024-05-03
2024-05-03
2024-05-03
2024-05-03
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0