From 881b826fb59a25102fd14ae3b420639479f2d6bf Mon Sep 17 00:00:00 2001 From: Matthew Holt Date: Wed, 27 May 2020 11:42:19 -0600 Subject: reverseproxy: Pool copy buffers (minor optimization) --- modules/caddyhttp/reverseproxy/streaming.go | 28 +++++++++++++--------------- 1 file changed, 13 insertions(+), 15 deletions(-) (limited to 'modules/caddyhttp/reverseproxy/streaming.go') diff --git a/modules/caddyhttp/reverseproxy/streaming.go b/modules/caddyhttp/reverseproxy/streaming.go index 0c8e338..170afe8 100644 --- a/modules/caddyhttp/reverseproxy/streaming.go +++ b/modules/caddyhttp/reverseproxy/streaming.go @@ -13,8 +13,8 @@ // limitations under the License. // Most of the code in this file was initially borrowed from the Go -// standard library, which has this copyright notice: -// Copyright 2011 The Go Authors. +// standard library and modified; It had this copyright notice: +// Copyright 2011 The Go Authors package reverseproxy @@ -24,6 +24,8 @@ import ( "net/http" "sync" "time" + + "go.uber.org/zap" ) func (h Handler) handleUpgradeResponse(rw http.ResponseWriter, req *http.Request, res *http.Response) { @@ -97,19 +99,8 @@ func (h Handler) copyResponse(dst io.Writer, src io.Reader, flushInterval time.D } } - // TODO: Figure out how we want to do this... using custom buffer pool type seems unnecessary - // or maybe it is, depending on how we want to handle errors, - // see: https://github.com/golang/go/issues/21814 - // buf := bufPool.Get().(*bytes.Buffer) - // buf.Reset() - // defer bufPool.Put(buf) - // _, err := io.CopyBuffer(dst, src, ) - var buf []byte - // if h.BufferPool != nil { - // buf = h.BufferPool.Get() - // defer h.BufferPool.Put(buf) - // } - // // we could also see about a pool that returns values like this: make([]byte, 32*1024) + buf := streamingBufPool.Get().([]byte) + defer streamingBufPool.Put(buf) _, err := h.copyBuffer(dst, src, buf) return err } @@ -131,6 +122,7 @@ func (h Handler) copyBuffer(dst io.Writer, src io.Reader, buf []byte) (int64, er // something we need to report to the client, but read errors are a problem on our // end for sure. so we need to decide what we want.) // p.logf("copyBuffer: ReverseProxy read error during body copy: %v", rerr) + h.logger.Error("reading from backend", zap.Error(rerr)) } if nr > 0 { nw, werr := dst.Write(buf[:nr]) @@ -221,3 +213,9 @@ func (c switchProtocolCopier) copyToBackend(errc chan<- error) { _, err := io.Copy(c.backend, c.user) errc <- err } + +var streamingBufPool = sync.Pool{ + New: func() interface{} { + return make([]byte, 32*1024) + }, +} -- cgit v1.2.3