go-zero/core/codec/gzip.go

37 lines
559 B
Go
Raw Normal View History

2020-07-26 17:09:05 +08:00
package codec
import (
"bytes"
"compress/gzip"
"io"
)
2020-10-16 10:50:43 +08:00
const unzipLimit = 100 * 1024 * 1024 // 100MB
2021-02-18 14:11:09 +08:00
// Gzip compresses bs.
2020-07-26 17:09:05 +08:00
func Gzip(bs []byte) []byte {
var b bytes.Buffer
w := gzip.NewWriter(&b)
w.Write(bs)
w.Close()
return b.Bytes()
}
2021-02-18 14:11:09 +08:00
// Gunzip uncompresses bs.
2020-07-26 17:09:05 +08:00
func Gunzip(bs []byte) ([]byte, error) {
r, err := gzip.NewReader(bytes.NewBuffer(bs))
if err != nil {
return nil, err
}
defer r.Close()
var c bytes.Buffer
2020-10-16 10:50:43 +08:00
if _, err = io.Copy(&c, io.LimitReader(r, unzipLimit)); err != nil {
2020-07-26 17:09:05 +08:00
return nil, err
}
return c.Bytes(), nil
}