-
Notifications
You must be signed in to change notification settings - Fork 8
/
compressed.go
45 lines (40 loc) · 1.07 KB
/
compressed.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
package bgc
import "bytes"
import (
"compress/gzip"
"github.com/viant/toolbox"
"io"
)
//Compressed represent compressed encoded payload
type Compressed struct {
output *bytes.Buffer
writer *gzip.Writer
encoderFactory toolbox.EncoderFactory
}
//Append append data to compressing stream
func (c *Compressed) Append(data map[string]interface{}) error {
return c.encoderFactory.Create(c.writer).Encode(&data)
}
//GetAndClose returns reader and cloases the stream
func (c *Compressed) GetAndClose() (io.Reader, error) {
var err error
if err = c.writer.Flush(); err != nil {
return nil, err
}
if err = c.writer.Close(); err != nil {
return nil, err
}
return bytes.NewReader(c.output.Bytes()), nil
}
//NewCompressed return new compressed struct
func NewCompressed(encoderFactory toolbox.EncoderFactory) *Compressed {
if encoderFactory == nil {
encoderFactory = toolbox.NewJSONEncoderFactory()
}
var result = &Compressed{
encoderFactory: encoderFactory,
output: new(bytes.Buffer),
}
result.writer = gzip.NewWriter(result.output)
return result
}