gin 框架基于中间件的身份验证和权限验证

本文介绍了一个使用 Gin 框架实现的路由匹配与 Django 风格的身份验证模块,包括自动匹配验证路由和自定义验证方式。核心内容涉及 JWT 令牌生成与解析,以及中间件拦截处理身份验证过程。
本模块创作基于gin 框架路由匹配和Django 的身份验证和权限验证创作的,目前主要实现了身份验证,基于路由配置自动匹配需要验证的路由,另外可以通过配置实现不同路由匹配不同身份验证方式 .
git地址: https://github.com/xxxxxxming/authtest
后续有时间持续更新该模块
模块主要由三个文件组成,分别是路由处理,身份认证,中间件拦截.  
代码如下:

1. 路由处理,包含路由数创建和路由解析
package utils

import (
	"bytes"
	"strings"
)

const (
	static nodeType = iota // default
	root
	param
	query
)

type nodeType uint8

type node struct {
   
   
	// 节点路径,比如上面的s,earch,和upport
	path string
	// 儿子节点
	children []*node
	nType    nodeType
	// 完整路径
	tokenAuth       string // token 校验
	permissionsAuth string // 权限校验
}

type methodTree struct {
   
   
	method string
	root   *node
}

type Engine struct {
   
   
	trees methodTrees
}

type methodTrees []methodTree

// 通过mothod 去获取该mothod 的路由树
func (trees methodTrees) get(method string) *node {
   
   
	for _, tree := range trees {
   
   
		if tree.method == method {
   
   
			return tree.root
		}
	}
	return nil
}

func assert1(guard bool, text string) {
   
   
	if !guard {
   
   
		panic(text)
	}
}

// 构建路由树
func (n *node) addRoute(path, tokenAuth, permissionsAuth string) {
   
   
	pathList := strings.Split(path, "/") // 获取url
	s := []byte(path)
	countSlash := uint16(bytes.Count(s, []byte("/"))) // 获取'/'的个数
	if countSlash == 0 {
   
   
		return
	}
	// 如果路由中只有一个'/',那么就直接赋值给根路径
	if countSlash == 1 && len(pathList) == 0 {
   
   
		n.nType = root
		n.path = "/"
		n.tokenAuth = tokenAuth
		n.permissionsAuth = permissionsAuth
	} else {
   
   
		// 构建子路由树
		n.insertChild(path, tokenAuth, permissionsAuth)
	}

}

// 获取url的列表,将位置参数和关键字参数都添加到列表中
func getUrlList(path string) []string {
   
   
	pathList := strings.Split(path, "/") // 获取url
	list := []string{
   
   }
	for _, p := range pathList {
   
    // 重新构造一个列表,其中包含位置参数和关键字参数
		if p == "" {
   
   
			continue
		}
		// 判断路径里面是否存在 关键字参数
		index := bytes.IndexByte([]byte(p), '?')
		if index == -1 {
   
   
			list = append(list, p)
		} else {
   
   
			// 将关键字参数作为一层子树放进列表中
			list = append(list, p[:index], p[index:])
		}
	}
	return list
}

func (n *node) insertChild(path, tokenAuth, permissionsAuth string) {
   
   
	list := getUrlList(path)
	head := n // 指向头节点的children

	llen := len(list)
	// 遍历路由列表和每层路由树
	for index1, l := range list {
   
   
		findflag := false
		// 开始遍历子树,从跟路由的子树开始遍历
		for index2, n1 := range head.children {
   
   
			// 当前子树中存在该路由
			if n1.path == l {
   
   
				if llen == index1+1 {
   
    // 遍历到了最后一个路径,将tokenAuth和permissionsAuth 赋值给该节点的tokenAuth和permissionsAuth
					n1.t
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值