forked from DataDog/datadog-agent
/
content_encoding.go
73 lines (61 loc) · 1.66 KB
/
content_encoding.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
70
71
72
73
// Unless explicitly stated otherwise all files in this repository are licensed
// under the Apache License Version 2.0.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2016-present Datadog, Inc.
package http
import (
"bytes"
"compress/gzip"
)
// ContentEncoding encodes the payload
type ContentEncoding interface {
name() string
encode(payload []byte) ([]byte, error)
}
// IdentityContentType encodes the payload using the identity function
var IdentityContentType ContentEncoding = &identityContentType{}
type identityContentType struct{}
func (c *identityContentType) name() string {
return "identity"
}
func (c *identityContentType) encode(payload []byte) ([]byte, error) {
return payload, nil
}
// GzipContentEncoding encodes the payload using gzip algorithm
type GzipContentEncoding struct {
level int
}
// NewGzipContentEncoding creates a new Gzip content type
func NewGzipContentEncoding(level int) *GzipContentEncoding {
if level < gzip.NoCompression {
level = gzip.NoCompression
} else if level > gzip.BestCompression {
level = gzip.BestCompression
}
return &GzipContentEncoding{
level,
}
}
func (c *GzipContentEncoding) name() string {
return "gzip"
}
func (c *GzipContentEncoding) encode(payload []byte) ([]byte, error) {
var compressedPayload bytes.Buffer
gzipWriter, err := gzip.NewWriterLevel(&compressedPayload, c.level)
if err != nil {
return nil, err
}
_, err = gzipWriter.Write(payload)
if err != nil {
return nil, err
}
err = gzipWriter.Flush()
if err != nil {
return nil, err
}
err = gzipWriter.Close()
if err != nil {
return nil, err
}
return compressedPayload.Bytes(), nil
}