-
Notifications
You must be signed in to change notification settings - Fork 654
/
io.go
68 lines (54 loc) · 1.12 KB
/
io.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package goflyway
import (
"io"
"net"
"sync/atomic"
. "github.com/coyove/goflyway/v"
)
func Bridge(target, source net.Conn, timeout *TokenBucket, stat *Traffic) {
go func() {
if err := ioCopy(target, source, timeout, stat.Sent()); err != nil {
Eprint("bridge: ", err)
}
target.Close()
source.Close()
}()
if err := ioCopy(source, target, timeout, stat.Recv()); err != nil {
Eprint("bridge: ", err)
}
// Multiple closes, but for tohConn they are just fine
target.Close()
source.Close()
}
func ioCopy(dst io.WriteCloser, src io.ReadCloser, bk *TokenBucket, bytes *int64) (err error) {
buf := make([]byte, 32*1024)
for {
nr, er := src.Read(buf)
if nr > 0 {
if bk != nil {
bk.Consume(int64(nr))
}
nw, ew := dst.Write(buf[0:nr])
if nw > 0 && bytes != nil {
atomic.AddInt64(bytes, int64(nw))
}
if ew != nil {
if !isClosedConnErr(ew) && !isTimeoutErr(ew) {
err = ew
}
break
}
if nr != nw {
err = io.ErrShortWrite
break
}
}
if er != nil {
if er != io.EOF && !isClosedConnErr(er) && !isTimeoutErr(er) {
err = er
}
break
}
}
return err
}