You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

content_encoding.go 1.1KB

12345678910111213141516171819202122232425262728293031323334
  1. package middleware
  2. import (
  3. "net/http"
  4. "strings"
  5. )
  6. // AllowContentEncoding enforces a whitelist of request Content-Encoding otherwise responds
  7. // with a 415 Unsupported Media Type status.
  8. func AllowContentEncoding(contentEncoding ...string) func(next http.Handler) http.Handler {
  9. allowedEncodings := make(map[string]struct{}, len(contentEncoding))
  10. for _, encoding := range contentEncoding {
  11. allowedEncodings[strings.TrimSpace(strings.ToLower(encoding))] = struct{}{}
  12. }
  13. return func(next http.Handler) http.Handler {
  14. fn := func(w http.ResponseWriter, r *http.Request) {
  15. requestEncodings := r.Header["Content-Encoding"]
  16. // skip check for empty content body or no Content-Encoding
  17. if r.ContentLength == 0 {
  18. next.ServeHTTP(w, r)
  19. return
  20. }
  21. // All encodings in the request must be allowed
  22. for _, encoding := range requestEncodings {
  23. if _, ok := allowedEncodings[strings.TrimSpace(strings.ToLower(encoding))]; !ok {
  24. w.WriteHeader(http.StatusUnsupportedMediaType)
  25. return
  26. }
  27. }
  28. next.ServeHTTP(w, r)
  29. }
  30. return http.HandlerFunc(fn)
  31. }
  32. }