go get github.com/dchest/captcha
import (
"bytes"
"net/http"
"time"
"github.com/dchest/captcha"
"github.com/gin-contrib/sessions"
"github.com/gin-contrib/sessions/cookie"
"github.com/gin-gonic/gin
}
func SessionConfig() sessions.Store {
sessionMaxAge := 3600
sessionSecret := "Psych"
store := cookie.NewStore([]byte(sessionSecret))
store.Options(sessions.Options{
MaxAge: sessionMaxAge,
Path: "/",
})
return store
}
处理session
func Session(keyPairs string) gin.HandlerFunc {
store:= SessionConfig()
return sessions.Sessions(keyPairs,store)
}
func Serve(w http.ResponseWriter, r *http.Request, id, ext, lang string, download bool, width, hight int) error {
w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
w.Header().Set("Pragma", "no-cache")
w.Header().Set("Expires", "0")
var content bytes.Buffer
switch ext {
case ".png":
w.Header().Set("Content-Type", "image/png")
_ = captcha.WriteImage(&content, id, width, hight)
case ".wav":
w.Header().Set("Content-Type", "audio/x-wav")
_ = captcha.WriteAudio(&content, id, lang)
default:
return captcha.ErrNotFound
}
if download {
w.Header().Set("Content-Type", "application/octet-stream")
}
http.ServeContent(w, r, id+ext, time.Time{}, bytes.NewReader(content.Bytes()))
return nil
}
func Captcha(c *gin.Context, lenght ...int) {
l := captcha.DefaultLen
w, h := 107, 36
if len(lenght) == 1 {
l = lenght[0]
}
if len(lenght) == 2 {
w = lenght[1]
}
if len(lenght) == 3 {
h = lenght[0]
}
captchaId := captcha.NewLen(l)
session := sessions.Default(c)
session.Set("captcha", captchaId)
_ = session.Save()
_ = Serve(c.Writer, c.Request, captchaId, ",png", "zh", false, w, h)
}
func CaptchaVerify(c *gin.Context, code string) bool {
session := sessions.Default(c)
if captchaId := session.Get("captcha"); captchaId != nil {
session.Delete("captcha")
_ = session.Save()
if captcha.VerifyString(captchaId.(string), code) {
return true
} else {
return false
}
} else {
return false
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>验证码</title>
</head>
<body>
<h1>Golang-gin-验证码</h1>
<form action="/captcha/verify" method="post">
User: <input type="text"><br>
Password: <input type="password"><br>
Captcha: <input type="text" name="code">
<img src="/captcha" onclick="this.src='/captcha?v='+Math.random()">
<input type="submit">
</form>
</body>
</html>
func main() {
router := gin.Default()
router.LoadHTMLGlob("./*.html")
router.Use(Session("Psych"))
router.GET("/captcha", func(c *gin.Context) {
Captcha(c, 4)
})
router.GET("/", func(c *gin.Context) {
c.HTML(http.StatusOK, "index.html", nil)
})
router.POST("/captcha/verify", func(c *gin.Context) {
value := c.PostForm("code")
if CaptchaVerify(c, value) {
c.JSON(http.StatusOK, gin.H{
"status": 0,
"msg": "success",
})
} else {
c.JSON(http.StatusOK, gin.H{
"status": 1,
"msg": "failed",
})
}
})
router.Run()
}