This commit is contained in:
oneao committed 2025-11-06 22:50:03 +08:00
1 parent d60be4a75b
commit be8eaae7c5
24 files changed
+595 -232

No files matched your search

@@ -1,6 +1,7 @@
package router
import (
"base-go-v2/internal/errs"
"base-go-v2/internal/utils/mapx"
"base-go-v2/internal/utils/validate"
"encoding/json"
@@ -154,3 +155,35 @@ func (c *Context) Text(statusCode int, msg string) error {
c.Abort()
return nil
}
// AddError 记录错误,自动包装 StackError
func (c *Context) AddError(err error) error {
if err == nil {
return nil
}
if c.keys == nil {
c.keys = make(map[string]interface{})
}
if _, exists := c.keys["errors"]; !exists {
c.keys["errors"] = []*errs.StackError{}
}
// 统一生成堆栈
se := errs.WrapWithStack(err)
c.keys["errors"] = append(c.keys["errors"].([]*errs.StackError), se)
return err
}
// Errors 返回 []*utils.StackError
func (c *Context) Errors() []*errs.StackError {
if c.keys == nil {
return nil
}
if err, exists := c.keys["errors"]; exists {
return err.([]*errs.StackError)
}
return nil
}
@@ -74,6 +74,7 @@ type middlewareEntry struct {
// 判断路径是否被排除
func (m *middlewareEntry) IsExcluded(path string) bool {
path = strings.TrimSuffix(path, "/") // 去掉尾部斜杠
if m.excludePaths != nil {
if _, ok := m.excludePaths[path]; ok {
return true
@@ -123,23 +124,36 @@ func (r *Router) Use(handler HandlerFunc) *MiddlewareHandle {
}
// ExcludePaths 支持 /** 前缀匹配
func (mh *MiddlewareHandle) ExcludePaths(paths ...string) *Router {
excludeMap := make(map[string]struct{}, 0)
// ExcludePaths 支持 /** 前缀匹配,并自动带上 basePath
func (mh *MiddlewareHandle) ExcludePaths(paths ...string) *MiddlewareHandle {
excludeMap := make(map[string]struct{})
excludePrefix := make([]string, 0)
basePath := strings.TrimSuffix(mh.router.basePath, "/") // 去掉尾部斜杠
for _, p := range paths {
if strings.HasSuffix(p, "/**") {
base := strings.TrimSuffix(p, "/**")
fullPath := p
if !strings.HasPrefix(p, "/") {
fullPath = "/" + p
}
// 自动加上 basePath
if basePath != "/" {
fullPath = basePath + fullPath
}
if strings.HasSuffix(fullPath, "/**") {
base := strings.TrimSuffix(fullPath, "/**")
excludePrefix = append(excludePrefix, base)
} else {
excludeMap[p] = struct{}{}
excludeMap[fullPath] = struct{}{}
}
}
mh.router.middleware[mh.entryIdx].excludePaths = excludeMap
mh.router.middleware[mh.entryIdx].excludePrefix = excludePrefix
return mh.router
return mh
}
// Group 创建子路由组