传统网站验证码工作机制
由于服务器生成的验证码值从始至终均未返回给客户端,因此,客户端只能从图片中识别验证码字符串,从而保证人机校验逻辑。
Go的HTTP验证码
Go 语言的 HTTP 服务器默认不支持 Session,因此验证码值需要换个思路存储,以下是不使用 Session 的逻辑
github.com/dchest/captcha
package main
import (
"fmt"
"github.com/dchest/captcha"
"log"
"net/http"
)
func main() {
// 获取验证码 ID
http.HandleFunc("/captcha/generate", func(w http.ResponseWriter, r *http.Request) {
id := captcha.NewLen(6)
if _, err := fmt.Fprint(w, id); err != nil {
log.Println("generate captcha error", err)
}
})
// 获取验证码图片
http.HandleFunc("/captcha/image", func(w http.ResponseWriter, r *http.Request) {
id := r.URL.Query().Get("id")
if id == "" {
http.Error(w, "Bad Request", http.StatusBadRequest)
return
}
w.Header().Set("Content-Type", "image/png")
if err := captcha.WriteImage(w, id, 120, 80); err != nil {
log.Println("show captcha error", err)
}
})
// 业务处理
http.HandleFunc("/login", func(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
log.Println("parseForm error", err)
http.Error(w, "Internal Error", http.StatusInternalServerError)
return
}
// 获取验证码 ID 和验证码值
id := r.FormValue("id")
value := r.FormValue("value")
// 比对提交的验证码值和内存中的验证码值
if captcha.VerifyString(id, value) {
fmt.Fprint(w, "ok")
} else {
fmt.Fprint(w, "mismatch")
}
})
log.Fatal(http.ListenAndServe(":8080", nil))
}
运行
https://github.com/xialeistudio/go-http-captcha-example
以上就是分享一个Golang Http 验证码示例的详细内容,更多请关注php中文网其它相关文章!
声明:本文转载于:segmentfault,如有侵犯,请联系admin@php.cn删除
程序员必备接口测试调试工具:点击使用
Apipost = Postman + Swagger + Mock + Jmeter
Api设计、调试、文档、自动化测试工具
网页生成APP,用做网站的技术去做APP:立即创建
手机网站开发APP、自助封装APP、200+原生模块、2000+映射JS接口按需打包
相关文章
相关视频