forked from elastic/beats
-
Notifications
You must be signed in to change notification settings - Fork 0
/
enc.go
66 lines (53 loc) · 1.21 KB
/
enc.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
package http
import (
"compress/gzip"
"errors"
"io"
"net/http"
"strings"
)
type contentEncoder interface {
AddHeaders(*http.Header)
Encode(to io.Writer, from io.Reader) error
}
type nilEncoder struct{}
type gzipEncoder struct {
gz *gzip.Writer
}
var plainEncoder = nilEncoder{}
func getContentEncoder(name string, level int) (contentEncoder, error) {
name = strings.ToLower(name)
if name == "gzip" {
return newGZIPEncoder(level)
}
if name != "" {
return nil, errors.New("invalid content encoder")
}
return plainEncoder, nil
}
func (nilEncoder) AddHeaders(_ *http.Header) {}
func (nilEncoder) Encode(to io.Writer, from io.Reader) error {
_, err := io.Copy(to, from)
return err
}
func newGZIPEncoder(level int) (*gzipEncoder, error) {
w, err := gzip.NewWriterLevel(nil, level)
if err != nil {
return nil, err
}
return &gzipEncoder{w}, nil
}
func (e *gzipEncoder) AddHeaders(h *http.Header) {
h.Add("Content-Type", "application/json; charset=UTF-8")
h.Add("Content-Encoding", "gzip")
}
func (e *gzipEncoder) Encode(to io.Writer, from io.Reader) error {
e.gz.Reset(to)
if _, err := io.Copy(e.gz, from); err != nil {
return err
}
if err := e.gz.Flush(); err != nil {
return err
}
return nil
}