This commit is contained in:
oneao committed 2025-11-01 17:29:25 +08:00
1 parent b116690769
commit 1d6bb2b7f5
23 files changed
+922 -116

No files matched your search

@@ -0,0 +1,24 @@
package middleware
import "base-go-v2/internal/router"
func CORSMiddleware() router.HandlerFunc {
return func(c *router.Context) error {
origin := string(c.RequestCtx.Request.Header.Peek("Origin"))
if origin == "" {
origin = "*"
}
c.RequestCtx.Response.Header.Set("Access-Control-Allow-Origin", origin)
c.RequestCtx.Response.Header.Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
c.RequestCtx.Response.Header.Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
c.RequestCtx.Response.Header.Set("Access-Control-Allow-Credentials", "true")
if string(c.RequestCtx.Method()) == "OPTIONS" {
c.RequestCtx.SetStatusCode(200)
return nil
}
return c.Next()
}
}
@@ -0,0 +1,29 @@
package middleware
import (
"base-go-v2/internal/logx"
"base-go-v2/internal/reponse"
"base-go-v2/internal/router"
"runtime/debug"
)
func ErrorMiddleware() router.HandlerFunc {
return func(c *router.Context) error {
err := c.Next()
if err != nil {
stack := string(debug.Stack())
logx.Logger.Error("请求错误",
logx.String("path", string(c.RequestCtx.Path())),
logx.String("method", string(c.RequestCtx.Method())),
logx.String("error", err.Error()),
logx.String("stack", stack),
)
return response.Error(c).Message(err.Error()).Send()
}
return nil
}
}
@@ -0,0 +1,43 @@
package middleware
import (
"base-go-v2/internal/logx"
"base-go-v2/internal/router"
"base-go-v2/internal/routinex"
"base-go-v2/internal/utils/uid"
"time"
)
// TrackTime 记录开始时间到现在时间的耗时
func TrackTime(pre time.Time) time.Duration {
elapsed := time.Since(pre)
return elapsed
}
func LoggerMiddleware() router.HandlerFunc {
return func(c *router.Context) error {
start := time.Now() // 记录开始时间
// 生成 trackID 并存入 routinex
trackID := uid.NextID()
routinex.Set(logx.TrackID, trackID)
// 执行业务逻辑,并捕获错误
err := c.Next()
// 请求结束后计算耗时
elapsed := TrackTime(start)
ip := c.RequestCtx.RemoteIP().String()
logx.Logger.Info("接口请求",
logx.String("path", string(c.RequestCtx.Path())),
logx.String("method", string(c.RequestCtx.Method())),
logx.String("ip", ip),
logx.Duration("elapsed", elapsed),
)
return err
}
}
@@ -0,0 +1,31 @@
package middleware
import (
"base-go-v2/internal/logx"
response "base-go-v2/internal/reponse"
"base-go-v2/internal/router"
"runtime/debug"
)
func RecoveryMiddleware() router.HandlerFunc {
return func(c *router.Context) error {
defer func() {
if r := recover(); r != nil {
stack := string(debug.Stack()) // 获取堆栈
logx.Logger.Error("请求 panic",
logx.String("path", string(c.RequestCtx.Path())),
logx.String("method", string(c.RequestCtx.Method())),
logx.String("panic", r.(error).Error()),
logx.String("stack", stack),
)
// 返回统一 JSON 响应
_ = response.Error(c).Message("系统 Panic").Send()
}
}()
// 调用后续 handler
return c.Next()
}
}