Files
eightbf-analysis-go/internal/api/middleware.go
T
gozerosandCursor bd427b57a1 feat: 换到 Gin 主流栈并补齐运维能力
HTTP 用 Gin,配置用 Viper,日志用 zap,数据用 sqlx;保留原有接口与会商行为。
顺带补上就绪探活、请求号、滚动日志、systemd 与 Dockerfile。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-04 09:51:41 +08:00

88 lines
2.2 KiB
Go

package api
import (
"crypto/rand"
"encoding/hex"
"net/http"
"time"
"github.com/gin-gonic/gin"
"git.gozeros.com/wsk/eightbf-analysis-go/internal/logging"
)
const reqIDKey = "reqId"
// RequestID 为每个请求分配 reqId(可读头 X-Request-Id),并做慢请求 WARN。
//
// 约定:调用方已带 X-Request-Id 就沿用,方便和 Nginx / 前端对上同一次操作。
// 边界:轮询 GET 不打 INFO,只有超过 3 秒才 WARN,避免作业查询把故障日志淹没。
func RequestID() gin.HandlerFunc {
return func(c *gin.Context) {
rid := c.GetHeader("X-Request-Id")
if rid == "" {
rid = newReqID()
}
c.Header("X-Request-Id", rid)
c.Set(reqIDKey, rid)
start := time.Now()
c.Next()
elapsed := time.Since(start)
if elapsed >= 3*time.Second {
logging.L.Warnw("慢请求",
logging.KeyReqID, rid,
"method", c.Request.Method,
"path", c.Request.URL.Path,
"ms", elapsed.Milliseconds(),
)
}
}
}
// RequestIDFrom 取出中间件写入的请求号。
func RequestIDFrom(c *gin.Context) string {
if c == nil {
return ""
}
v, ok := c.Get(reqIDKey)
if !ok {
return ""
}
s, _ := v.(string)
return s
}
func newReqID() string {
b := make([]byte, 8)
_, _ = rand.Read(b)
return "req_" + hex.EncodeToString(b)
}
// CORS 本机联调放开跨域。经 Nginx 同源反代时浏览器不会走这段,多写无副作用。
func CORS() gin.HandlerFunc {
return func(c *gin.Context) {
h := c.Writer.Header()
h.Set("Access-Control-Allow-Origin", "*")
h.Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
h.Set("Access-Control-Allow-Headers", "*")
h.Set("Access-Control-Expose-Headers", "X-Request-Id")
if c.Request.Method == http.MethodOptions {
c.AbortWithStatus(http.StatusNoContent)
return
}
c.Next()
}
}
// Recovery 接住 handler panic,记一条错误日志并回 500,避免 Gin 默认文本把响应外壳弄乱。
func Recovery() gin.HandlerFunc {
return gin.CustomRecovery(func(c *gin.Context, rec interface{}) {
logging.L.Errorw("接口 panic",
logging.KeyReqID, RequestIDFrom(c),
"path", c.Request.URL.Path,
"err", rec,
)
Fail(c, http.StatusInternalServerError, 500, "internal error")
})
}