...

Source file src/github.com/go-chi/chi/middleware/content_charset.go

Documentation: github.com/go-chi/chi/middleware

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

View as plain text