-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpipe.go
76 lines (68 loc) · 1.42 KB
/
pipe.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
69
70
71
72
73
74
75
76
package main
import (
"io"
"net"
)
type readResult struct {
data []byte
err error
}
// chanFromConn creates a channel from a Conn object, and sends everything it
// Read()s from the socket to the channel.
// channel delivers {[]byte, nil} after successfull read.
// channel delivers {nil,err} in case of error.
// channel is closed when EOF is received.
func chanFromConn(conn net.Conn) chan readResult {
c := make(chan readResult)
go func() {
// make buffer to receive data
buf := make([]byte, 1024)
for {
n, err := conn.Read(buf)
if n > 0 {
res := make([]byte, n)
// Copy the buffer so it doesn't get changed while read by the recipient.
copy(res, buf[:n])
c <- readResult{res, nil}
}
if err == io.EOF {
close(c)
return
}
if err != nil {
c <- readResult{nil, err}
break
}
}
}()
return c
}
// Pipe creates a full-duplex pipe between the two sockets and transfers data from one to the other.
func Pipe(conn1 net.Conn, conn2 net.Conn) (e1, e2 error) {
chan1 := chanFromConn(conn1)
chan2 := chanFromConn(conn2)
for {
select {
case b1, ok := <-chan1:
if !ok {
return // connection was closed
}
if b1.err != nil {
e1 = b1.err
return
} else {
conn2.Write(b1.data)
}
case b2, ok := <-chan2:
if !ok {
return // connection was closed
}
if b2.err != nil {
e2 = b2.err
return
} else {
conn1.Write(b2.data)
}
}
}
}