-
Notifications
You must be signed in to change notification settings - Fork 3
/
compress.go
69 lines (65 loc) · 1.2 KB
/
compress.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
63
64
65
66
67
68
69
package datautils
import (
"bytes"
"compress/gzip"
"compress/zlib"
"fmt"
"io"
)
const (
None = iota
GZip
Zlib
)
func Compress(data []byte, compressType int) ([]byte, error) {
var b bytes.Buffer
switch compressType {
case GZip:
gz := gzip.NewWriter(&b)
if _, err := gz.Write(data); err != nil {
return nil, err
}
if err := gz.Close(); err != nil {
return nil, err
}
return b.Bytes(), nil
case Zlib:
zl := zlib.NewWriter(&b)
if _, err := zl.Write(data); err != nil {
return nil, err
}
if err := zl.Close(); err != nil {
return nil, err
}
return b.Bytes(), nil
}
return nil, fmt.Errorf("compression type not found")
}
func Decompress(data []byte, compressType int) ([]byte, error) {
b := bytes.NewReader(data)
switch compressType {
case GZip:
gz, err := gzip.NewReader(b)
if err != nil {
return nil, err
}
defer gz.Close()
raw, err := io.ReadAll(gz)
if err != nil {
return nil, err
}
return raw, nil
case Zlib:
zl, err := zlib.NewReader(b)
if err != nil {
return nil, err
}
defer zl.Close()
raw, err := io.ReadAll(zl)
if err != nil {
return nil, err
}
return raw, nil
}
return nil, fmt.Errorf("compression type not found")
}