github.com/nyan233/littlerpc@v0.4.6-0.20230316182519-0c8d5c48abaf/core/middle/packer/packet_gzip.go (about) 1 package packer 2 3 import ( 4 "bytes" 5 "compress/gzip" 6 "io/ioutil" 7 ) 8 9 type Gzip struct{} 10 11 func (g *Gzip) Scheme() string { 12 return "gzip" 13 } 14 15 func (g *Gzip) UnPacket(p []byte) ([]byte, error) { 16 gr, err := gzip.NewReader(bytes.NewReader(p)) 17 if err != nil { 18 return nil, err 19 } 20 defer gr.Close() 21 p, err = ioutil.ReadAll(gr) 22 if err.Error() == "unexpected EOF" { 23 return p, nil 24 } else { 25 return p, err 26 } 27 } 28 29 func (g *Gzip) EnPacket(p []byte) ([]byte, error) { 30 var bb bytes.Buffer 31 gw, _ := gzip.NewWriterLevel(&bb, gzip.BestCompression) 32 defer gw.Close() 33 _, err := gw.Write(p) 34 if err != nil { 35 return nil, err 36 } 37 gw.Flush() 38 return bb.Bytes(), nil 39 }