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_charset.go 1.3KB

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