49 lines
1.2 KiB
Go
49 lines
1.2 KiB
Go
package main
|
|
|
|
import (
|
|
"bytes"
|
|
"errors"
|
|
"log/slog"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"testing"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
func TestRequestLoggerDoesNotLogResponseBody(t *testing.T) {
|
|
gin.SetMode(gin.TestMode)
|
|
|
|
var logBuffer bytes.Buffer
|
|
previousLogger := slog.Default()
|
|
slog.SetDefault(slog.New(slog.NewTextHandler(&logBuffer, &slog.HandlerOptions{})))
|
|
defer slog.SetDefault(previousLogger)
|
|
|
|
router := gin.New()
|
|
router.Use(requestLogger())
|
|
router.GET("/fail", func(c *gin.Context) {
|
|
_ = c.Error(errors.New("root cause"))
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "do not log this body"})
|
|
})
|
|
|
|
rec := httptest.NewRecorder()
|
|
req := httptest.NewRequest(http.MethodGet, "/fail?debug=1", nil)
|
|
router.ServeHTTP(rec, req)
|
|
|
|
if rec.Code != http.StatusBadRequest {
|
|
t.Fatalf("expected 400, got %d", rec.Code)
|
|
}
|
|
|
|
logOutput := logBuffer.String()
|
|
if !strings.Contains(logOutput, "request failed") {
|
|
t.Fatalf("expected request failure log, got %q", logOutput)
|
|
}
|
|
if strings.Contains(logOutput, "do not log this body") {
|
|
t.Fatalf("response body leaked into logs: %q", logOutput)
|
|
}
|
|
if !strings.Contains(logOutput, "root cause") {
|
|
t.Fatalf("expected error details in logs, got %q", logOutput)
|
|
}
|
|
}
|