Преглед изворни кода

Reuse buffers on socket pumping

tags/0.9
9seconds пре 7 година
родитељ
комит
2c938d2848
2 измењених фајлова са 29 додато и 8 уклоњено
  1. 16
    0
      proxy/copy_pool.go
  2. 13
    8
      proxy/server.go

+ 16
- 0
proxy/copy_pool.go Прегледај датотеку

@@ -0,0 +1,16 @@
1
+package proxy
2
+
3
+import "sync"
4
+
5
+const copyBufferSize = 30 * 1024
6
+
7
+var copyPool sync.Pool
8
+
9
+func init() {
10
+	copyPool = sync.Pool{
11
+		New: func() interface{} {
12
+			data := make([]byte, copyBufferSize)
13
+			return &data
14
+		},
15
+	}
16
+}

+ 13
- 8
proxy/server.go Прегледај датотеку

@@ -83,14 +83,10 @@ func (s *Server) accept(conn net.Conn) {
83 83
 
84 84
 	wait := &sync.WaitGroup{}
85 85
 	wait.Add(2)
86
-	go func() {
87
-		defer wait.Done()
88
-		io.Copy(clientConn, tgConn) // nolint: errcheck
89
-	}()
90
-	go func() {
91
-		defer wait.Done()
92
-		io.Copy(tgConn, clientConn) // nolint: errcheck
93
-	}()
86
+
87
+	go s.pipe(clientConn, tgConn, wait)
88
+	go s.pipe(tgConn, clientConn, wait)
89
+
94 90
 	<-ctx.Done()
95 91
 	wait.Wait()
96 92
 
@@ -131,6 +127,15 @@ func (s *Server) getTelegramStream(ctx context.Context, cancel context.CancelFun
131 127
 	return conn, nil
132 128
 }
133 129
 
130
+func (s *Server) pipe(dst io.Writer, src io.Reader, wait *sync.WaitGroup) {
131
+	defer wait.Done()
132
+
133
+	buf := copyPool.Get().(*[]byte)
134
+	defer copyPool.Put(buf)
135
+
136
+	io.CopyBuffer(dst, src, *buf) // nolint: errcheck
137
+}
138
+
134 139
 // NewServer creates new instance of MTPROTO proxy.
135 140
 func NewServer(conf *config.Config, logger *zap.SugaredLogger, stat *Stats) *Server {
136 141
 	return &Server{

Loading…
Откажи
Сачувај