-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdatablock.go
237 lines (211 loc) · 6.21 KB
/
datablock.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
package datablock
import (
"bytes"
"compress/gzip"
"github.com/mattetti/filebuffer"
log "github.com/sirupsen/logrus"
"io"
"io/ioutil"
"net/http"
"strconv"
"time"
)
// DataBlock represents a block of data that may be compressed
type DataBlock struct {
data []byte
compressed bool
length int
compressionSpeed bool // prefer speed over best compression ratio?
}
var (
// EmptyDataBlock is an empty data block
EmptyDataBlock = &DataBlock{[]byte{}, false, 0, true}
)
// NewDataBlock creates a new uncompressed data block.
// compressionSpeed is if speedy compression should be used over compact compression
func NewDataBlock(data []byte, compressionSpeed bool) *DataBlock {
return &DataBlock{data, false, len(data), compressionSpeed}
}
// Create a new data block where the data may already be compressed.
// compressionSpeed is if speedy compression should be used over compact compression
func newDataBlockSpecified(data []byte, compressed bool, compressionSpeed bool) *DataBlock {
return &DataBlock{data, compressed, len(data), compressionSpeed}
}
// UncompressedData returns the the original, uncompressed data,
// the length of the data and an error. Will decompress if needed.
func (b *DataBlock) UncompressedData() ([]byte, int, error) {
if b.compressed {
return decompress(b.data)
}
return b.data, b.length, nil
}
// MustData returns the uncompressed data or an empty byte slice
func (b *DataBlock) MustData() []byte {
if b.compressed {
data, _, err := decompress(b.data)
if err != nil {
log.Fatal(err)
return []byte{}
}
return data
}
return b.data
}
// Bytes returns the uncompressed data or an empty byte slice
func (b *DataBlock) Bytes() []byte {
return b.MustData()
}
// String returns the uncompressed data as a string or as an empty string.
// Same as MustData, but converted to a string.
func (b *DataBlock) String() string {
return string(b.MustData())
}
// Gzipped returns the compressed data, length and an error.
// Will compress if needed.
func (b *DataBlock) Gzipped() ([]byte, int, error) {
if !b.compressed {
return compress(b.data, b.compressionSpeed)
}
return b.data, b.length, nil
}
// Compress this data block
func (b *DataBlock) Compress() error {
if b.compressed {
return nil
}
data, bytesWritten, err := compress(b.data, b.compressionSpeed)
if err != nil {
return err
}
b.data = data
b.compressed = true
b.length = bytesWritten
return nil
}
// Decompress this data block
func (b *DataBlock) Decompress() error {
if !b.compressed {
return nil
}
data, bytesWritten, err := decompress(b.data)
if err != nil {
return err
}
b.data = data
b.compressed = false
b.length = bytesWritten
return nil
}
// IsCompressed checks if this data block is compressed
func (b *DataBlock) IsCompressed() bool {
return b.compressed
}
// StringLength returns the length of the data, represented as a string
func (b *DataBlock) StringLength() string {
return strconv.Itoa(b.length)
}
// Length returns the lentgth of the current data
// (not the length of the original data, but in the current state)
func (b *DataBlock) Length() int {
return b.length
}
// HasData returns true if there is data present
func (b *DataBlock) HasData() bool {
return 0 != b.length
}
// ToClient writes the data to the client.
// Also sets the right headers and compresses the data with gzip if needed.
// Set canGzip to true if the http client can handle gzipped data.
// gzipThreshold is the threshold (in bytes) for when it makes sense to compress the data with gzip
func (b *DataBlock) ToClient(w http.ResponseWriter, req *http.Request, name string, canGzip bool, gzipThreshold int) {
overThreshold := b.Length() > gzipThreshold // Is there enough data that it makes sense to compress it?
// Compress or decompress the data as needed. Add headers if compression is used.
if !canGzip {
// No compression
if err := b.Decompress(); err != nil {
// Unable to decompress gzipped data!
log.Fatal(err)
}
} else if b.compressed || overThreshold {
// If the given data is already compressed, or we are planning to compress,
// set the gzip headers and serve it as compressed data.
w.Header().Set("Content-Encoding", "gzip")
w.Header().Add("Vary", "Accept-Encoding")
// If the data is over a certain size, compress and serve
if overThreshold {
// Compress
if err := b.Compress(); err != nil {
// Write uncompressed data if gzip should fail
log.Error(err)
w.Header().Set("Content-Encoding", "identity")
}
}
}
// Done by ServeContent instead
//w.Header().Set("Content-Length", b.StringLength())
//w.Write(b.data)
// Serve the data with http.ServeContent, which supports ranges/streaming
http.ServeContent(w, req, name, time.Time{}, filebuffer.New(b.data))
}
// Compress data using gzip. Returns the data, data length and an error.
func compress(data []byte, speed bool) ([]byte, int, error) {
if len(data) == 0 {
return []byte{}, 0, nil
}
var buf bytes.Buffer
_, err := gzipWrite(&buf, data, speed)
if err != nil {
return nil, 0, err
}
data = buf.Bytes()
return data, len(data), nil
}
// Decompress data using gzip. Returns the data, data length and an error.
func decompress(data []byte) ([]byte, int, error) {
if len(data) == 0 {
return []byte{}, 0, nil
}
var buf bytes.Buffer
_, err := gunzipWrite(&buf, data)
if err != nil {
return nil, 0, err
}
data = buf.Bytes()
return data, len(data), nil
}
// Write gzipped data to a Writer. Returns bytes written and an error.
func gzipWrite(w io.Writer, data []byte, speed bool) (int, error) {
// Write gzipped data to the client
level := gzip.BestCompression
if speed {
level = gzip.BestSpeed
}
gw, err := gzip.NewWriterLevel(w, level)
if err != nil {
return 0, err
}
defer gw.Close()
bytesWritten, err := gw.Write(data)
if err != nil {
return 0, err
}
return bytesWritten, nil
}
// Write gunzipped data to a Writer. Returns bytes written and an error.
func gunzipWrite(w io.Writer, data []byte) (int, error) {
// Write gzipped data to the client
gr, err := gzip.NewReader(bytes.NewBuffer(data))
if err != nil {
return 0, err
}
defer gr.Close()
data, err = ioutil.ReadAll(gr)
if err != nil {
return 0, err
}
bytesWritten, err := w.Write(data)
if err != nil {
return 0, err
}
return bytesWritten, nil
}