diff --git a/middleware/content_charset.go b/middleware/content_charset.go index 07b5ce6f..44f7e246 100644 --- a/middleware/content_charset.go +++ b/middleware/content_charset.go @@ -14,6 +14,11 @@ func ContentCharset(charsets ...string) func(next http.Handler) http.Handler { return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.ContentLength == 0 { + next.ServeHTTP(w, r) + return + } + if !contentEncoding(r.Header.Get("Content-Type"), charsets...) { w.WriteHeader(http.StatusUnsupportedMediaType) return diff --git a/middleware/content_charset_test.go b/middleware/content_charset_test.go index aee06a2d..e7b6f7f5 100644 --- a/middleware/content_charset_test.go +++ b/middleware/content_charset_test.go @@ -15,56 +15,72 @@ func TestContentCharset(t *testing.T) { name string inputValue string inputContentCharset []string + contentLength int64 want int }{ { "should accept requests with a matching charset", "application/json; charset=UTF-8", []string{"UTF-8"}, + 100, http.StatusOK, }, { "should be case-insensitive", "application/json; charset=utf-8", []string{"UTF-8"}, + 100, http.StatusOK, }, { "should accept requests with a matching charset with extra values", "application/json; foo=bar; charset=UTF-8; spam=eggs", []string{"UTF-8"}, + 100, http.StatusOK, }, { "should accept requests with a matching charset when multiple charsets are supported", "text/xml; charset=UTF-8", []string{"UTF-8", "Latin-1"}, + 100, http.StatusOK, }, { "should accept requests with no charset if empty charset headers are allowed", "text/xml", []string{"UTF-8", ""}, + 100, http.StatusOK, }, { "should not accept requests with no charset if empty charset headers are not allowed", "text/xml", []string{"UTF-8"}, + 100, http.StatusUnsupportedMediaType, }, { "should not accept requests with a mismatching charset", "text/plain; charset=Latin-1", []string{"UTF-8"}, + 100, http.StatusUnsupportedMediaType, }, { "should not accept requests with a mismatching charset even if empty charsets are allowed", "text/plain; charset=Latin-1", []string{"UTF-8", ""}, + 100, http.StatusUnsupportedMediaType, }, + { + "should skip charset validation if ContentLength is 0", + "text/plain; charset=Latin-1", + []string{"UTF-8"}, + 0, + http.StatusOK, + }, } for _, tt := range tests {