-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathbodyWriter.go
102 lines (86 loc) · 2.23 KB
/
bodyWriter.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
package compress
/*
gin-compress Copyright (C) 2022 Aurora McGinnis
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
import (
"bytes"
"github.com/gin-gonic/gin"
"io"
)
// respWriter wraps the default request writer to allow for compressing the request contents. It uses an internal buffer
// until threshold is hit, at which point it switches to the compressor.
// If threshold is never hit, calling Close() will copy the buffer contents to the response writer
type respWriter struct {
gin.ResponseWriter
threshold int
encoding string
algo algorithm
buf *bytes.Buffer
bytesWritten int
compressor io.WriteCloser
}
func newResponseWriter(c *gin.Context, swapSize int, encoding string, algo algorithm) *respWriter {
return &respWriter{
c.Writer,
swapSize,
encoding,
algo,
bytes.NewBuffer(nil),
0,
nil,
}
}
func (rw *respWriter) WriteString(s string) (int, error) {
return rw.Write([]byte(s))
}
func (rw *respWriter) Write(b []byte) (int, error) {
rw.Header().Del("Content-Length")
if !rw.Swapped() && rw.buf.Len()+len(b) >= rw.threshold {
rw.ResponseWriter.Header().Set("Content-Encoding", rw.encoding)
rw.ResponseWriter.Header().Set("Vary", "Accept-Encoding")
rw.compressor = rw.algo.getWriter(rw.ResponseWriter)
if copied, err := io.Copy(rw.compressor, rw.buf); err != nil {
return int(copied), err
}
rw.buf = nil
}
var w io.Writer
if rw.Swapped() {
w = rw.compressor
} else {
w = rw.buf
}
if n, err := w.Write(b); err != nil {
return n, err
} else {
rw.bytesWritten += n
return n, err
}
}
func (rw *respWriter) Size() int {
return rw.bytesWritten
}
func (rw *respWriter) Written() bool {
return rw.bytesWritten > 0
}
func (rw *respWriter) Close() error {
if !rw.Swapped() {
// buf was never switched...
if _, err := io.Copy(rw.ResponseWriter, rw.buf); err != nil {
return err
}
} else {
return rw.compressor.Close()
}
return nil
}
func (rw *respWriter) Swapped() bool {
return rw.buf == nil
}
func (rw *respWriter) WriteHeader(code int) {
rw.Header().Del("Content-Length")
rw.ResponseWriter.WriteHeader(code)
}