feat: add Recovery middleware for panic handling with verbose logging

This commit is contained in:
GitHub Actions
2025-11-30 22:19:38 +00:00
parent b2bcbe86bb
commit 48fbca2eee
2 changed files with 97 additions and 0 deletions

View File

@@ -0,0 +1,27 @@
package middleware
import (
"log"
"net/http"
"runtime/debug"
"github.com/gin-gonic/gin"
)
// Recovery logs panic information. When verbose is true it logs stacktraces
// and basic request metadata for debugging.
func Recovery(verbose bool) gin.HandlerFunc {
return func(c *gin.Context) {
defer func() {
if r := recover(); r != nil {
if verbose {
log.Printf("PANIC: %v\nRequest: %s %s\nHeaders: %v\nStacktrace:\n%s", r, c.Request.Method, c.Request.URL.String(), c.Request.Header, debug.Stack())
} else {
log.Printf("PANIC: %v", r)
}
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "internal server error"})
}
}()
c.Next()
}
}

View File

@@ -0,0 +1,70 @@
package middleware
import (
"bytes"
"log"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/gin-gonic/gin"
)
func TestRecoveryLogsStacktraceVerbose(t *testing.T) {
old := log.Writer()
buf := &bytes.Buffer{}
log.SetOutput(buf)
defer log.SetOutput(old)
router := gin.New()
router.Use(Recovery(true))
router.GET("/panic", func(c *gin.Context) {
panic("test panic")
})
req := httptest.NewRequest(http.MethodGet, "/panic", nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusInternalServerError {
t.Fatalf("expected status 500, got %d", w.Code)
}
out := buf.String()
if !strings.Contains(out, "PANIC: test panic") {
t.Fatalf("log did not include panic message: %s", out)
}
if !strings.Contains(out, "Stacktrace:") {
t.Fatalf("verbose log did not include stack trace: %s", out)
}
}
func TestRecoveryLogsBriefWhenNotVerbose(t *testing.T) {
old := log.Writer()
buf := &bytes.Buffer{}
log.SetOutput(buf)
defer log.SetOutput(old)
router := gin.New()
router.Use(Recovery(false))
router.GET("/panic", func(c *gin.Context) {
panic("brief panic")
})
req := httptest.NewRequest(http.MethodGet, "/panic", nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusInternalServerError {
t.Fatalf("expected status 500, got %d", w.Code)
}
out := buf.String()
if !strings.Contains(out, "PANIC: brief panic") {
t.Fatalf("log did not include panic message: %s", out)
}
if strings.Contains(out, "Stacktrace:") {
t.Fatalf("non-verbose log unexpectedly included stacktrace: %s", out)
}
}