Skip to content

Commit 62ddd1a

Browse files
committed
fix: OPTIONS request should not be processed by gzip
1 parent 6e0cff3 commit 62ddd1a

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

handler_test.go

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -412,3 +412,32 @@ func TestHTTPWithDefaultHandler_TinyPayload_WriteThreeTimes(t *testing.T) {
412412
assert.Empty(t, result.Header.Get("Content-Encoding"))
413413
assert.Equal(t, "part 1\npart 2\npart 3\n", w.Body.String())
414414
}
415+
416+
func TestGinCORSMiddleware(t *testing.T) {
417+
var (
418+
g = newGinInstance(bigPayload, DefaultHandler().Gin, corsMiddleware)
419+
r = httptest.NewRequest(http.MethodOptions, "/", nil)
420+
w = httptest.NewRecorder()
421+
)
422+
423+
g.ServeHTTP(w, r)
424+
result := w.Result()
425+
426+
assert.EqualValues(t, http.StatusNoContent, result.StatusCode)
427+
assert.Equal(t, "*", result.Header.Get("Access-Control-Allow-Origin"))
428+
assert.Equal(t, "POST", result.Header.Get("Access-Control-Allow-Methods"))
429+
assert.EqualValues(t, 0, w.Body.Len())
430+
}
431+
432+
// corsMiddleware allows CORS request
433+
func corsMiddleware(c *gin.Context) {
434+
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
435+
c.Writer.Header().Set("Access-Control-Allow-Methods", "POST")
436+
437+
if c.Request.Method == http.MethodOptions {
438+
c.AbortWithStatus(http.StatusNoContent)
439+
return
440+
}
441+
442+
c.Next()
443+
}

requestfilters.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ func NewCommonRequestFilter() *CommonRequestFilter {
3333
// ShouldCompress implements RequestFilter interface
3434
func (c *CommonRequestFilter) ShouldCompress(req *http.Request) bool {
3535
return req.Method != http.MethodHead &&
36+
req.Method != http.MethodOptions &&
3637
req.Header.Get("Upgrade") == "" &&
3738
strings.Contains(req.Header.Get("Accept-Encoding"), "gzip")
3839
}

0 commit comments

Comments
 (0)