Open
Description
Add an AllowContentType middleware
Checklist
- [ x] Dependencies installed
- [ x] No typos
- [ x] Searched existing issues and docs
Expected behaviour
This is a very handy middleware available in Chi. I thought it would be a good idea to have one in echo.
Actual behaviour
N/A
Steps to reproduce
N/A
Working code to debug
func AllowContentType(contentTypes ...string) echo.MiddlewareFunc {
if len(contentTypes) == 0 {
panic("echo: allow-content middleware requires a valida content-type")
}
allowedContentTypes := make(map[string]struct{}, len(contentTypes))
for _, ctype := range contentTypes {
allowedContentTypes[strings.TrimSpace(strings.ToLower(ctype))] = struct{}{}
}
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
if c.Request().ContentLength == 0 {
// skip check for empty content body
return next(c)
}
s := strings.ToLower(strings.TrimSpace(c.Request().Header.Get("Content-Type")))
if i := strings.Index(s, ";"); i > -1 {
s = s[0:i]
}
if _, ok := allowedContentTypes[s]; ok {
return next(c)
}
return echo.NewHTTPError(http.StatusUnsupportedMediaType)
}
}
}
Version/commit
Metadata
Metadata
Assignees
Labels
No labels