From 35cf6d27b82a01da12a38e6c66b6305368fb6927 Mon Sep 17 00:00:00 2001 From: tiennam Date: Tue, 5 Dec 2023 23:16:29 +0700 Subject: [PATCH] feat: add buffer pool --- internal/proxy/buffer_pool.go | 30 ++++++++++++++++++++++++++++++ internal/proxy/proxy.go | 1 + 2 files changed, 31 insertions(+) create mode 100644 internal/proxy/buffer_pool.go diff --git a/internal/proxy/buffer_pool.go b/internal/proxy/buffer_pool.go new file mode 100644 index 0000000..6f362a1 --- /dev/null +++ b/internal/proxy/buffer_pool.go @@ -0,0 +1,30 @@ +package proxy + +import ( + "net/http/httputil" + "sync" +) + +const DefaultMaxBufferSize = 1024 * 32 // MB + +type bufferPool struct { + pool sync.Pool +} + +func (b *bufferPool) Get() []byte { + return b.pool.Get().([]byte) +} + +func (b *bufferPool) Put(bytes []byte) { + b.pool.Put(bytes) // nolint:staticcheck +} + +func newBufferPool() httputil.BufferPool { + return &bufferPool{ + pool: sync.Pool{ + New: func() interface{} { + return make([]byte, DefaultMaxBufferSize) + }, + }, + } +} diff --git a/internal/proxy/proxy.go b/internal/proxy/proxy.go index 2cb145c..fc8727e 100644 --- a/internal/proxy/proxy.go +++ b/internal/proxy/proxy.go @@ -169,6 +169,7 @@ func (h *Proxy) AddTarget(target TargetConfig, index uint) error { // proxy.ModifyResponse = h.doModifyResponse(target) // nolint:bodyclose proxy.ErrorHandler = h.doErrorHandler(target, index) + proxy.BufferPool = newBufferPool() h.targets = append( h.targets,