Golang使用验证码

使用的第三方库

go get github.com/dchest/captcha
package main

import (
	"fmt"
	"github.com/dchest/captcha"
	"io"
	"log"
	"net/http"
	"text/template"
)

var formTemplate = template.Must(template.New("example").Parse(formTemplateSrc))

func showFormHandler(w http.ResponseWriter, r *http.Request) {
	d := struct {
		CaptchaId string
	}{
		captcha.New(),
	}
	if err := formTemplate.Execute(w, &d); err != nil {
		// 处理错误,500 服务器异常
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
}

func processFormHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	// VerifyString方法用来验证并删除验证码,因为验证之后验证码就没存在的意义了
	// captchaId是标识验证码的ID,captchaSolution是客户输入的数字
	if !captcha.VerifyString(r.FormValue("captchaId"), r.FormValue("captchaSolution")) {
		io.WriteString(w, "错误的验证码解决方案!不允许机器人!\n")
	} else {
		io.WriteString(w, "伟大的人类!你破解了验证码。\n")
	}
	io.WriteString(w, "<br><a href='/'>再试一次</a>")
}

func main() {
	http.HandleFunc("/", showFormHandler)  // 验证码主页面
	http.HandleFunc("/process", processFormHandler)  // 验证客户端发送过来的验证码是否正确
	http.Handle("/captcha/", captcha.Server(captcha.StdWidth, captcha.StdHeight))  // 图像的生成,并返回图片
	fmt.Println("服务运行于: http://localhost:8666")
	if err := http.ListenAndServe("localhost:8666", nil); err != nil {
		log.Fatal(err)
	}
}

const formTemplateSrc = `
<!doctype html>
<head><title>验证码</title></head>
<body>
<script>
function reload() {
    setSrcQuery(document.getElementById('image'), "reload=" + (new Date()).getTime());
    return false;
}
</script>
<form action="/process" method=post>
<p>输入你在下面的图片中看到的数字:</p>
<p><img id=image src="/captcha/{{.CaptchaId}}.png" alt="Captcha image"></p>
<input type=hidden name=captchaId value="{{.CaptchaId}}"><br>
<input name=captchaSolution>
<input type=submit value=提交>
</form>
`

运行后访问页面:
在这里插入图片描述
输入正确后跳转:
在这里插入图片描述
输入错误后跳转:
在这里插入图片描述

[]