Go语言学习笔记——gin实现验证码

文章目录

  • Golang验证码
    • 知识结构
    • 下载包
    • 导包
    • 配置session
    • 创建中间件
    • 生成图片
    • 生成验证码
    • 验证
    • 前端页面
    • 测试


Golang验证码

知识结构

  1. gin
  2. session中间件
  3. 表单处理
  4. 路由

下载包

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 

你可能感兴趣的:(Go精进,学习,gin)