github.com/scottcagno/storage@v1.8.0/pkg/web/buffer.go (about) 1 package web 2 3 import ( 4 "bytes" 5 "sync" 6 ) 7 8 var ( 9 initBufferPool sync.Once 10 bufferPool *BufferPool 11 ) 12 13 type BufferPool struct { 14 pool sync.Pool 15 } 16 17 func newBufferPool() *BufferPool { 18 return &BufferPool{ 19 pool: sync.Pool{ 20 New: func() interface{} { 21 return new(bytes.Buffer) 22 }, 23 }, 24 } 25 } 26 27 // OpenBufferPool returns a single instance of the buffer pool 28 // utilizing sync.Once which gives us a no-brainier implementation 29 // of the classic singleton pattern 30 func OpenBufferPool() *BufferPool { 31 initBufferPool.Do(func() { 32 bufferPool = newBufferPool() 33 }) 34 return bufferPool 35 } 36 37 func (bp *BufferPool) Get() *bytes.Buffer { 38 return bp.pool.Get().(*bytes.Buffer) 39 } 40 41 func (bp *BufferPool) Put(buf *bytes.Buffer) { 42 buf.Reset() 43 bp.pool.Put(buf) 44 }