This commit is contained in:
Samuel Berthe
2023-10-21 19:56:15 +02:00
2 changed files with 18 additions and 5 deletions
+9 -3
View File
@@ -8,18 +8,24 @@ import (
type bodyWriter struct {
gin.ResponseWriter
body *bytes.Buffer
body *bytes.Buffer
maxSize int
}
// implements gin.ResponseWriter
func (w bodyWriter) Write(b []byte) (int, error) {
w.body.Write(b)
if w.body.Len()+len(b) > w.maxSize {
w.body.Write(b[:w.maxSize-w.body.Len()])
} else {
w.body.Write(b)
}
return w.ResponseWriter.Write(b)
}
func newBodyWriter(writer gin.ResponseWriter) *bodyWriter {
func newBodyWriter(writer gin.ResponseWriter, maxSize int) *bodyWriter {
return &bodyWriter{
body: bytes.NewBufferString(""),
ResponseWriter: writer,
maxSize: maxSize,
}
}
+9 -2
View File
@@ -20,6 +20,9 @@ const (
)
var (
RequestBodyMaxSize = 64 * 1024 // 64KB
ResponseBodyMaxSize = 64 * 1024 // 64KB
HiddenRequestHeaders = map[string]struct{}{
"authorization": {},
"cookie": {},
@@ -105,13 +108,17 @@ func NewWithConfig(logger *slog.Logger, config Config) gin.HandlerFunc {
buf, err := io.ReadAll(c.Request.Body)
if err == nil {
c.Request.Body = io.NopCloser(bytes.NewBuffer(buf))
reqBody = buf
if len(buf) > RequestBodyMaxSize {
reqBody = buf[:RequestBodyMaxSize]
} else {
reqBody = buf
}
}
}
// dump response body
if config.WithResponseBody {
c.Writer = newBodyWriter(c.Writer)
c.Writer = newBodyWriter(c.Writer, ResponseBodyMaxSize)
}
c.Next()