-
Notifications
You must be signed in to change notification settings - Fork 9
/
compress.go
55 lines (46 loc) · 1.16 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
package awos
import (
"bytes"
"compress/gzip"
"io"
"sync"
)
var (
compressTypeGzip = "gzip"
compressorsMu sync.RWMutex
compressors = make(map[string]Compressor)
)
func Register(comp Compressor) {
compressorsMu.Lock()
defer compressorsMu.Unlock()
compressors[comp.ContentEncoding()] = comp
}
type Compressor interface {
Compress(reader io.ReadSeeker) (gzipReader io.ReadSeeker, len int64, err error)
ContentEncoding() string
}
type GzipCompressor struct{}
func (g *GzipCompressor) Compress(reader io.ReadSeeker) (gzipReader io.ReadSeeker, len int64, err error) {
var buffer bytes.Buffer
gzipWriter := gzip.NewWriter(&buffer)
_, err = io.Copy(gzipWriter, reader)
if err != nil {
return nil, 0, err
}
err = gzipWriter.Close()
if err != nil {
return nil, 0, err
}
return bytes.NewReader(buffer.Bytes()), int64(buffer.Len()), nil
}
func (g *GzipCompressor) ContentEncoding() string {
return compressTypeGzip
}
var DefaultGzipCompressor = &GzipCompressor{}
func GetReaderLength(reader io.ReadSeeker) (io.ReadSeeker, int, error) {
all, err := io.ReadAll(reader)
if err != nil {
return nil, 0, err
}
return bytes.NewReader(all), len(all), nil
}