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