-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmiddleware.go
174 lines (140 loc) · 3.97 KB
/
middleware.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
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 (
"io"
"sort"
"strconv"
"strings"
"github.com/gin-gonic/gin"
)
type compressMiddleware struct {
cfg *compressOptions
}
func newCompressMiddleware(opts *compressOptions) (cm *compressMiddleware) {
cm = &compressMiddleware{
cfg: opts,
}
return
}
func (cm *compressMiddleware) Handler(c *gin.Context) {
if cf, err := cm.decompressRequest(c); err != nil {
_ = c.AbortWithError(400, err)
return
} else if cf != nil {
defer cf()
}
algo := cm.selectAlgorithm(c)
if algo == "" || !cm.shouldCompress(c) {
c.Next()
return
}
rw := newResponseWriter(c, cm.cfg.minCompressBytes, algo, algorithms[algo])
c.Writer = rw
c.Next()
_ = rw.Close()
}
// decompresses the request body, if one exists and Content-Encoding is specified
func (cm *compressMiddleware) decompressRequest(c *gin.Context) (func() error, error) {
if cm.cfg.skipDecompressRequest {
return nil, nil
}
encodings := strings.Split(strings.ReplaceAll(c.GetHeader("Content-Encoding"), " ", ""), ",")
if len(encodings) == 0 || c.Request.Body == nil {
// nothing to do
return nil, nil
}
// Content-Encodings are specified in the order they were applied,
// so we need to unapply them in the reverse order
readers := make([]io.ReadCloser, 0, len(encodings))
i := len(encodings) - 1
for ; i >= (len(encodings)-cm.cfg.maxDecodeSteps) && i >= 0; i-- {
enc := encodings[i]
w := c.Request.Body
if len(readers) > 0 {
w = readers[len(readers)-1]
}
if algo, ok := algorithms[enc]; ok {
r := algo.getReader(w)
readers = append(readers, r)
} else {
break
}
}
if len(readers) == 0 {
return nil, nil
}
c.Request.Header.Del("Content-Length")
if i <= -1 {
c.Request.Header.Del("Content-Encoding")
} else {
c.Request.Header.Set("Content-Encoding", strings.Join(encodings[:i+1], ", "))
}
br := &compressedBodyReader{
decomps: readers,
}
c.Request.Body = br
return br.Close, nil
}
type acceptableEncoding struct {
encoding string
q int
}
func (cm *compressMiddleware) selectAlgorithm(c *gin.Context) string {
acceptEncodings := strings.ToLower(strings.ReplaceAll(c.GetHeader("Accept-Encoding"), " ", ""))
if acceptEncodings == "" {
return ""
}
allowedEncodings := getEnabledAlgorithms()
// parse the Accept-Encoding header
encodings := strings.Split(acceptEncodings, ",")
acceptableEncodings := make([]acceptableEncoding, 0, len(encodings))
for _, encoding := range encodings {
parts := strings.Split(encoding, ";")
acc := acceptableEncoding{
encoding: parts[0],
q: 1000,
}
if len(parts) > 1 && strings.HasPrefix(parts[1], "q=") {
q, err := strconv.ParseFloat(parts[1][2:], 64)
if err != nil {
_ = c.Error(err)
} else {
acc.q = int(q * 1000)
}
}
// exclude any encodings that are not supported
if _, ok := allowedEncodings[acc.encoding]; ok && acc.q > 0 {
acceptableEncodings = append(acceptableEncodings, acc)
}
}
if len(acceptableEncodings) == 0 {
// could not agree upon an algo
return ""
}
// sort the encodings by q-value first, then their priorities
sort.Slice(acceptableEncodings, func(i int, j int) bool {
a, b := acceptableEncodings[i], acceptableEncodings[j]
if a.q == b.q {
alA, alB := allowedEncodings[a.encoding], allowedEncodings[b.encoding]
return alA.getConfig().priority < alB.getConfig().priority
} else {
return a.q < b.q
}
})
return acceptableEncodings[len(acceptableEncodings)-1].encoding
}
func (cm *compressMiddleware) shouldCompress(c *gin.Context) bool {
if strings.Contains(c.GetHeader("Accept"), "text/event-stream") ||
strings.Contains(c.GetHeader("Connection"), "Upgrade") {
return false
}
if cm.cfg.excludeFunc != nil && cm.cfg.excludeFunc(c) {
return false
}
return len(getEnabledAlgorithms()) > 0
}