This commit is contained in:
oneao committed 2025-08-15 17:27:23 +08:00
1 parent 428d370874
commit b408533fe7
15 files changed
+710 -97

No files matched your search

@@ -2,15 +2,29 @@ package middleware
import (
"base-framework/pkg/reponse"
"strings"
"base-framework/pkg/router"
"os"
"path/filepath"
"runtime"
"strings"
"sync"
)
// 仅初始化一次的项目信息
var (
initOnce sync.Once
projectBase string // 例:base-farmework
projectAbsPrefix string // 例:/abs/path/to/base-farmework/
projectAbsPrefixLower string // 小写版,用于不区分大小写前缀比较(Windows 安全)
)
// Error 中间件:捕获 c.Errors() 并返回统一的 ErrorInfo
func Error() router.HandlerFunc {
// 注册时预热(只做一次)
initOnce.Do(initProjectInfo)
return func(c *router.Context) {
c.Next() // 执行后续 Handler
c.Next()
errs := c.Errors()
if len(errs) == 0 {
@@ -25,8 +39,8 @@ func Error() router.HandlerFunc {
Method: c.Request.Method,
Path: c.Request.URL.Path,
Message: lastErr.Error(),
Stack: stack, // 完整堆栈
Location: location, // 业务 Handler 文件行号
Stack: stack,
Location: location,
}
reponse.Error(c).ErrorInfo(info).Send()
@@ -34,34 +48,111 @@ func Error() router.HandlerFunc {
}
}
// extractBusinessLocation:获取 AddError 后的业务 Handler 文件行号
// 仅在注册时执行:确定 go.mod 根目录并缓存前缀
func initProjectInfo() {
// 以当前源文件为起点向上找 go.mod
_, file, _, _ := runtime.Caller(0)
if root, ok := findGoModRoot(file); ok {
projectBase = filepath.Base(root)
p := filepath.ToSlash(root)
if !strings.HasSuffix(p, "/") {
p += "/"
}
projectAbsPrefix = p
projectAbsPrefixLower = strings.ToLower(p)
}
}
// extractBusinessLocation:获取 AddError 后的业务 Handler 文件行(仅返回 <project>/<subpath>.go:<line>)
func extractBusinessLocation(stack string) string {
lines := strings.Split(stack, "\n")
foundAddError := false
countGo := 0
for _, line := range lines {
line = strings.TrimSpace(line)
for _, raw := range lines {
line := strings.TrimSpace(raw)
if strings.Contains(line, "AddError") {
foundAddError = true
continue
}
if foundAddError && strings.Contains(line, ".go:") {
if !foundAddError {
continue
}
if strings.Contains(line, ".go:") {
countGo++
if countGo == 2 { // 第2个 .go: 行就是业务 Handler
// 去掉 +0x偏移
if idx := strings.Index(line, " +"); idx != -1 {
line = line[:idx]
if countGo == 2 {
// 去掉 " +0x..." 偏移
if i := strings.Index(line, " +"); i != -1 {
line = line[:i]
}
// 保留 base-farmework 开头的路径
slash := strings.Index(line, "base-farmework")
if slash != -1 {
line = line[slash:]
}
return line
return trimToProject(line)
}
}
}
return ""
}
// 将绝对路径裁剪为 "<project>/<subpath>.go:<line>"
func trimToProject(goLine string) string {
// 统一斜杠
line := strings.ReplaceAll(goLine, "\\", "/")
// 用最后一个冒号分离(避免 Windows 盘符)
idx := strings.LastIndex(line, ":")
if idx == -1 || idx+1 >= len(line) {
return line
}
filePath, lineNo := line[:idx], line[idx+1:]
// 优先:前缀裁剪(O(1)),比 filepath.Rel 更快
if projectAbsPrefix != "" {
fp := filepath.ToSlash(filePath)
fpl := strings.ToLower(fp)
if strings.HasPrefix(fpl, projectAbsPrefixLower) {
rel := fp[len(projectAbsPrefix):]
return projectBase + "/" + rel + ":" + lineNo
}
}
// 其次:internal/cmd/pkg 作为锚点
segs := strings.Split(filePath, "/")
for i, s := range segs {
if s == "internal" || s == "cmd" || s == "pkg" {
if i > 0 {
return strings.Join(segs[i-1:], "/") + ":" + lineNo
}
}
}
return ""
// 启发式:目录名包含 '-' 或 '_',当作仓库名
for i, s := range segs {
if strings.ContainsAny(s, "-_") {
return strings.Join(segs[i:], "/") + ":" + lineNo
}
}
// 兜底:末尾 4 级
start := len(segs) - 4
if start < 0 {
start = 0
}
return strings.Join(segs[start:], "/") + ":" + lineNo
}
// 从给定文件路径向上查找包含 go.mod 的目录(仅注册时调用一次)
func findGoModRoot(filePath string) (string, bool) {
dir := filepath.Clean(filepath.Dir(filepath.FromSlash(filePath)))
for {
if _, err := os.Stat(filepath.Join(dir, "go.mod")); err == nil {
return dir, true
}
parent := filepath.Dir(dir)
if parent == dir {
return "", false
}
dir = parent
}
}