-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcompress.go
More file actions
65 lines (53 loc) · 1.08 KB
/
compress.go
File metadata and controls
65 lines (53 loc) · 1.08 KB
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
package main
import (
"bytes"
"compress/flate"
"compress/gzip"
"errors"
"io"
"github.com/andybalholm/brotli"
)
// Compress byte slice.
func Compress(content []byte) ([]byte, error) {
if len(content) == 0 {
return nil, errors.New("no input data")
}
var b bytes.Buffer
w, err := gzip.NewWriterLevel(&b, flate.BestCompression)
if err != nil {
return nil, err
}
size, err := w.Write(content)
if err != nil {
return nil, err
}
if size == 0 {
return nil, errors.New("zero size compression output")
}
err = w.Close()
if err != nil {
return nil, err
}
return b.Bytes(), nil
}
// CompressBrotli for better compression than gzip.
func CompressBrotli(content []byte) ([]byte, error) {
if len(content) == 0 {
return nil, errors.New("no input data")
}
opt := brotli.WriterOptions{
Quality: 5,
}
b := bytes.Buffer{}
w := brotli.NewWriterOptions(&b, opt)
if w == nil {
return nil, errors.New("couldn't allocate writer")
}
defer w.Close()
in := bytes.NewReader(content)
_, err := io.Copy(w, in)
if err != nil {
return nil, err
}
return b.Bytes(), nil
}