forked from nzlov/forwardingproxy
/
debugconn.go
48 lines (40 loc) · 926 Bytes
/
debugconn.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package fproxy
import (
"fmt"
"io"
"net"
"go.uber.org/zap"
)
func netDirection(dest, src net.Conn) string {
return fmt.Sprintf("%s-%s-%s-%s", src.RemoteAddr(), src.LocalAddr(), dest.LocalAddr(), dest.RemoteAddr())
}
func newDebugReadCloser(r io.ReadCloser, direction string, logger *zap.Logger) io.ReadCloser {
return &debugReadCloser{
ReadCloser: r,
Direction: direction,
Logger: logger,
}
}
type debugReadCloser struct {
io.ReadCloser
*zap.Logger
Direction string
n int
}
func (r *debugReadCloser) Read(p []byte) (n int, err error) {
n, err = r.ReadCloser.Read(p)
if n > 0 {
r.n += n
r.Logger.Debug("transferred",
zap.String("direction", r.Direction),
zap.Int("bytes", n),
zap.Int("total", r.n))
}
if err != nil {
r.Logger.Debug("read error",
zap.String("direction", r.Direction),
zap.Int("total", r.n),
zap.String("error", err.Error()))
}
return n, err
}