-
Notifications
You must be signed in to change notification settings - Fork 5
/
gzip.go
62 lines (54 loc) · 1.42 KB
/
gzip.go
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
59
60
61
62
package gzip
import (
"bytes"
"compress/gzip"
"github.com/arquivei/foundationkit/errors"
)
// Compress the @input using the gzip format
func Compress(input []byte) ([]byte, error) {
const op = errors.Op("gzip.Compress")
var buf bytes.Buffer
zw := gzip.NewWriter(&buf)
_, err := zw.Write(input)
if err != nil {
return nil, errors.E(op, err)
}
err = zw.Close()
if err != nil {
return nil, errors.E(op, err)
}
return buf.Bytes(), nil
}
// MustCompress compresses @input using gzip, and panic if it fails
func MustCompress(input []byte) []byte {
const op = errors.Op("gzip.MustCompress")
output, err := Compress(input)
if err != nil {
panic(errors.E(op, err))
}
return output
}
// Decompress @input in the gzip format
func Decompress(input []byte) ([]byte, error) {
const op = errors.Op("gzip.Decompress")
b := bytes.NewReader(input)
r, err := gzip.NewReader(b)
if err != nil {
return nil, errors.E(op, err, errors.KV("step", "gzip.NewReader"))
}
var responseBuffer bytes.Buffer
_, err = responseBuffer.ReadFrom(r)
if err != nil {
return nil, errors.E(op, err, errors.KV("step", "responseBuffer.ReadFrom"))
}
return responseBuffer.Bytes(), nil
}
// MustDecompress decompresses @input in the gzip format, and panic if it fails
func MustDecompress(input []byte) []byte {
const op = errors.Op("gzip.MustDecompress")
output, err := Decompress(input)
if err != nil {
panic(errors.E(op, err))
}
return output
}