本模块创作基于gin 框架路由匹配和Django 的身份验证和权限验证创作的,目前主要实现了身份验证,基于路由配置自动匹配需要验证的路由,另外可以通过配置实现不同路由匹配不同身份验证方式 .
git地址: https://github.com/xxxxxxming/authtest
后续有时间持续更新该模块
模块主要由三个文件组成,分别是路由处理,身份认证,中间件拦截.
代码如下:
1. 路由处理,包含路由数创建和路由解析
package utils
import (
"bytes"
"strings"
)
const (
static nodeType = iota
root
param
query
)
type nodeType uint8
type node struct {
path string
children []*node
nType nodeType
tokenAuth string
permissionsAuth string
}
type methodTree struct {
method string
root *node
}
type Engine struct {
trees methodTrees
}
type methodTrees []methodTree
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, "/")
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)
}
}
func getUrlList(path string) []string {
pathList := strings.Split(path, "/")
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
llen := len(list)
for index1, l := range list {
findflag := false
for index2, n1 := range head.children {
if n1.path == l {
if llen == index1+1 {
n1.t