feat(http): 统一可信字段注入与可选日志恢复能力
Verify / verify (push) Canceled after 0s

This commit is contained in:
zhangdeman committed 2026-11-28 02:51:21 -08:00
1 parent 568e516b1a
commit 7ea7b153a2
10 files changed
+595 -46

No files matched your search

+55
View File
@@ -0,0 +1,55 @@
// Package recovery 捕获 Gin 请求 panic,允许应用显式提供报告和响应协议。
package recovery
import (
"fmt"
"net/http"
"runtime/debug"
"git.zhangdeman.cn/zhangdeman/ginframework/fault"
"git.zhangdeman.cn/zhangdeman/ginframework/logger"
"github.com/gin-gonic/gin"
)
const codePanic = 900901
// Incident 只包含 panic 类型和单次采集的调用栈,不保存原始 panic 值。
type Incident struct {
Type string `json:"type" dc:"panic 动态类型,不调用其格式化方法"`
Stack []byte `json:"-" dc:"本次恢复的单次调用栈,仅供内部诊断"`
}
// Options 指定 panic 的诊断和安全响应边界。
type Options struct {
Report func(*gin.Context, Incident) `json:"-" dc:"同步记录一次 panic,nil 使用框架安全错误日志"`
Respond func(*gin.Context) `json:"-" dc:"未提交响应时调用的安全响应函数,nil 返回通用 JSON 500"`
}
// New 创建 panic 恢复中间件;入参为应用协议回调,返回 Gin Handler。
// 仅恢复当前请求协程,不吞掉普通 error;报告后中止处理链。
// 响应已提交(包括 SSE Flush)时不追加 JSON 或改写状态,仍报告并 Abort。
// 不拥有日志资源;应用负责回调的并发安全和不泄漏诊断内容。
func New(options Options) gin.HandlerFunc {
return func(ctx *gin.Context) {
defer func() {
if recovered := recover(); recovered != nil {
incident := Incident{Type: fmt.Sprintf("%T", recovered), Stack: debug.Stack()}
ctx.Abort()
if options.Report != nil {
options.Report(ctx, incident)
} else {
logger.RecordErrorContext(ctx.Request.Context(), "recover HTTP handler panic", fault.New(codePanic, "recover HTTP handler panic", nil))
}
if ctx.Writer.Written() {
return
}
if options.Respond != nil {
options.Respond(ctx)
} else {
ctx.JSON(http.StatusInternalServerError, gin.H{"code": http.StatusInternalServerError, "message": "Internal Server Error"})
}
}
}()
ctx.Next()
}
}
+56
View File
@@ -0,0 +1,56 @@
package recovery
import (
"net/http/httptest"
"strings"
"testing"
"github.com/gin-gonic/gin"
)
type sensitivePanic struct{}
func (sensitivePanic) String() string { panic("formatter must not be invoked") }
func TestCustomRecoveryAndCommittedStream(t *testing.T) {
for _, stream := range []bool{false, true} {
reports, responses := 0, 0
engine := gin.New()
engine.Use(New(Options{Report: func(_ *gin.Context, incident Incident) {
reports++
if !strings.Contains(incident.Type, "sensitivePanic") || !strings.Contains(string(incident.Stack), "TestCustomRecoveryAndCommittedStream") {
t.Fatal("missing diagnostic")
}
}, Respond: func(ctx *gin.Context) { responses++; ctx.JSON(503, gin.H{"message": "safe"}) }}))
engine.GET("/panic", func(ctx *gin.Context) {
if stream {
ctx.SSEvent("ready", "hello")
ctx.Writer.Flush()
}
panic(sensitivePanic{})
}, func(*gin.Context) { t.Fatal("continued after panic") })
out := httptest.NewRecorder()
engine.ServeHTTP(out, httptest.NewRequest("GET", "/panic", nil))
if reports != 1 {
t.Fatalf("reports=%d", reports)
}
if stream {
if responses != 0 || out.Code != 200 || !out.Flushed || strings.Contains(out.Body.String(), "safe") {
t.Fatal("stream rewritten")
}
} else if responses != 1 || out.Code != 503 {
t.Fatal("custom response missing")
}
}
}
func TestDefaultRecoveryHidesValue(t *testing.T) {
engine := gin.New()
engine.Use(New(Options{}))
engine.GET("/panic", func(*gin.Context) { panic("private-token") })
out := httptest.NewRecorder()
engine.ServeHTTP(out, httptest.NewRequest("GET", "/panic", nil))
if out.Code != 500 || strings.Contains(out.Body.String(), "private-token") {
t.Fatalf("unsafe default: %s", out.Body.String())
}
}
Reference in new issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.