github.com/keysonZZZ/kmg@v0.0.0-20151121023212-05317bfd7d39/kmgCompress/flate.go (about) 1 package kmgCompress 2 3 import ( 4 "bytes" 5 "compress/flate" 6 "io/ioutil" 7 ) 8 9 //flate压缩,panic+buffer实现 10 // 会由于 11 func FlateMustCompress(inb []byte) (outb []byte) { 12 buf := &bytes.Buffer{} 13 w, err := flate.NewWriter(buf, -1) 14 if err != nil { 15 panic(err) //只会由于加密level设置错误而报错 但是上面明显是对的. 16 } 17 _, err = w.Write(inb) 18 if err != nil { 19 w.Close() 20 panic(err) 21 } 22 err = w.Close() 23 if err != nil { 24 panic(err) // 全部代码看过,只会由于w.Write错误而报错, 但是明显w.Write 不会报错. 25 } 26 return buf.Bytes() 27 } 28 29 func FlateMustUnCompress(inb []byte) (outb []byte) { 30 buf := bytes.NewBuffer(inb) 31 reader := flate.NewReader(buf) 32 outb, err := ioutil.ReadAll(reader) 33 if err != nil { 34 reader.Close() 35 panic(err) 36 } 37 err = reader.Close() 38 if err != nil { 39 panic(err) 40 } 41 return outb 42 } 43 44 func FlateUnCompress(inb []byte) (outb []byte, err error) { 45 buf := bytes.NewBuffer(inb) 46 reader := flate.NewReader(buf) 47 outb, err = ioutil.ReadAll(reader) 48 if err != nil { 49 reader.Close() 50 return nil, err 51 } 52 err = reader.Close() 53 if err != nil { 54 return 55 } 56 return outb, nil 57 }