Golang 实现的高级安全验证码
发表时间: 2024-05-31 10:42
github地址:
github.com/dchest/captcha
go get -u github.com/dchest/captcha
package mainimport ( "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))}
运行
访问/captcha/generate获得验证码 ID
访问/captcha/image?id=验证码 ID
访问/login,并输入第一步的验证码 ID 和第二步的验证码值即可查看验证结果
完整代码:
https://github.com/xialeistudio/go-http-captcha-example。