content_charset.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package middleware
  2. import (
  3. "net/http"
  4. "slices"
  5. "strings"
  6. )
  7. // ContentCharset generates a handler that writes a 415 Unsupported Media Type response if none of the charsets match.
  8. // An empty charset will allow requests with no Content-Type header or no specified charset.
  9. func ContentCharset(charsets ...string) func(next http.Handler) http.Handler {
  10. for i, c := range charsets {
  11. charsets[i] = strings.ToLower(c)
  12. }
  13. return func(next http.Handler) http.Handler {
  14. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  15. if !contentEncoding(r.Header.Get("Content-Type"), charsets...) {
  16. w.WriteHeader(http.StatusUnsupportedMediaType)
  17. return
  18. }
  19. next.ServeHTTP(w, r)
  20. })
  21. }
  22. }
  23. // Check the content encoding against a list of acceptable values.
  24. func contentEncoding(ce string, charsets ...string) bool {
  25. _, ce = split(strings.ToLower(ce), ";")
  26. _, ce = split(ce, "charset=")
  27. ce, _ = split(ce, ";")
  28. return slices.Contains(charsets, ce)
  29. }
  30. // Split a string in two parts, cleaning any whitespace.
  31. func split(str, sep string) (string, string) {
  32. a, b, found := strings.Cut(str, sep)
  33. a = strings.TrimSpace(a)
  34. if found {
  35. b = strings.TrimSpace(b)
  36. }
  37. return a, b
  38. }