1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
| type Compresser interface { Compress(data []byte, name string) ([]byte, error) UnCompress([]byte) ([]byte, error) }
type noOpCompress struct { }
func (n noOpCompress) Compress(data []byte, name string) ([]byte, error) { return data, nil }
func (n noOpCompress) UnCompress(msg []byte) ([]byte, error) { return msg, nil }
type zipCompress struct { }
func (n zipCompress) Compress(data []byte, name string) (res []byte, err error) { defer func() { if r := recover(); r != nil { if e, ok := r.(error); ok { err = e } return } }()
var buffer bytes.Buffer wt := zip.NewWriter(&buffer) hw, err := wt.Create(name) CheckError(err) _, err = hw.Write(data) CheckError(err) _ = wt.Close() return buffer.Bytes(), nil }
func (n zipCompress) UnCompress(msg []byte) ([]byte, error) { reader := bytes.NewReader(msg) var writer bytes.Buffer zreader, err := zip.NewReader(reader, reader.Size()) if err != nil { return nil, err } for _, name := range zreader.File { rdwt, err := name.Open() if err != nil { return nil, err } _, _ = io.Copy(&writer, rdwt) _ = rdwt.Close() return writer.Bytes(), nil } return nil, nil }
|