Fast and extensible multi-platform HTTP/1-2-3 web server with automatic HTTPS
Mirrored from https://github.com/Slazee/caddy.git
Synced Nov 13, 04:15 UTC
caddyhttp: Log request body bytes read (#5461)
Francis Lavoie committed
Mar 27, 2023 at 18:40 UTC
2b3046de36bad70bd7e48478c99a8a030fb35b98
1 file changed
+32
modules/caddyhttp/server.go
+32
@@ -19,6 +19,7 @@ import (
19
"crypto/tls"
20
"encoding/json"
21
"fmt"
22
+ "io"
23
"net"
24
"net/http"
25
"net/netip"
@@ -259,6 +260,14 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
260
wrec := NewResponseRecorder(w, nil, nil)
261
w = wrec
262
263
+ // wrap the request body in a LengthReader
264
+ // so we can track the number of bytes read from it
265
+ var bodyReader *lengthReader
266
+ if r.Body != nil {
267
+ bodyReader = &lengthReader{Source: r.Body}
268
+ r.Body = bodyReader
269
+ }
270
+
271
// capture the original version of the request
272
accLog := s.accessLogger.With(loggableReq)
273
@@ -285,7 +294,13 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
294
295
userID, _ := repl.GetString("http.auth.user.id")
296
297
+ reqBodyLength := 0
298
+ if bodyReader != nil {
299
+ reqBodyLength = bodyReader.Length
300
+ }
301
+
302
log("handled request",
303
+ zap.Int("bytes_read", reqBodyLength),
304
zap.String("user_id", userID),
305
zap.Duration("duration", duration),
306
zap.Int("size", wrec.Size()),
@@ -826,6 +841,23 @@ func cloneURL(from, to *url.URL) {
841
}
842
}
843
844
+// lengthReader is an io.ReadCloser that keeps track of the
845
+// number of bytes read from the request body.
846
+type lengthReader struct {
847
+ Source io.ReadCloser
848
+ Length int
849
+}
850
+
851
+func (r *lengthReader) Read(b []byte) (int, error) {
852
+ n, err := r.Source.Read(b)
853
+ r.Length += n
854
+ return n, err
855
+}
856
+
857
+func (r *lengthReader) Close() error {
858
+ return r.Source.Close()
859
+}
860
+
861
// Context keys for HTTP request context values.
862
const (
863
// For referencing the server instance