1 // Package gzip provides an Encoder for the httpbuffer package that uses gzip 2 // compression. 3 package gzip // import "vimagination.zapto.org/httpbuffer/gzip" 4 5 import ( 6 "compress/gzip" 7 "io" 8 "sync" 9 10 "vimagination.zapto.org/httpbuffer" 11 ) 12 13 type gzipWriter struct { 14 *gzip.Writer 15 } 16 17 func (g gzipWriter) WriteString(str string) (int, error) { 18 return g.Write([]byte(str)) 19 } 20 21 var ( 22 // Compression sets the compression level for the gzip encoder 23 Compression = gzip.BestCompression 24 25 pool = sync.Pool{ 26 New: func() interface{} { 27 g, _ := gzip.NewWriterLevel(nil, Compression) 28 return gzipWriter{g} 29 }, 30 } 31 ) 32 33 type encoding struct{} 34 35 func (encoding) Open(w io.Writer) io.Writer { 36 g := pool.Get().(gzipWriter) 37 g.Reset(w) 38 return g 39 } 40 41 func (encoding) Close(w io.Writer) { 42 g := w.(gzipWriter) 43 g.Close() 44 pool.Put(w) 45 } 46 47 func (encoding) Name() string { 48 return "gzip" 49 } 50 51 type encodingX struct { 52 encoding 53 } 54 55 func (encodingX) Name() string { 56 return "x-gzip" 57 } 58 59 func init() { 60 httpbuffer.Register(encoding{}) 61 httpbuffer.Register(encodingX{}) 62 }