-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathinterco.go
More file actions
52 lines (45 loc) · 868 Bytes
/
interco.go
File metadata and controls
52 lines (45 loc) · 868 Bytes
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
package main
import (
"io"
"net"
"sync"
"github.com/golang/snappy"
)
// interconnect c1 to c2 with optional snappy compression/decompression
// both c1 and c2 will be closed on completion
func interco(c1, c2 net.Conn, compress bool) {
cl := make(chan struct{})
once := sync.Once{}
doClose := func() {
once.Do(func() {
close(cl)
})
}
// closing both connections will trigger read failure and close the following goroutines
defer c1.Close()
defer c2.Close()
// c1→c2
go func() {
defer doClose()
if compress {
// snappy compression
w := snappy.NewBufferedWriter(c1)
io.Copy(w, c2)
w.Close()
} else {
io.Copy(c1, c2)
}
}()
// c2→c1
go func() {
defer doClose()
if compress {
// snappy decompression
io.Copy(c2, snappy.NewReader(c1))
} else {
io.Copy(c2, c1)
}
}()
// wait for close signal
<-cl
}