log/body_byte_counter.go (18 lines of code) (raw):
package log
import (
"io"
"sync/atomic"
)
// bodyByteCounter is a wrapper for http.Request.Body that counts bytes read.
type bodyByteCounter struct {
body io.ReadCloser
count *atomic.Int64
}
// bodyByteCounter implements io.ReadCloser.
var _ io.ReadCloser = &bodyByteCounter{}
// Read implements the io.Reader interface, counting bytes as they are read.
func (c *bodyByteCounter) Read(p []byte) (int, error) {
n, err := c.body.Read(p)
c.count.Add(int64(n))
return n, err
}
// Close implements the io.Closer interface.
func (c *bodyByteCounter) Close() error {
return c.body.Close()
}