Golang验证码
知识结构
- gin
- session中间件
- 表单处理
- 路由
下载包
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
}
配置session
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