-
-
Notifications
You must be signed in to change notification settings - Fork 2.2k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add an AllowContentType middleware (based on chi) #2551
Comments
Why not rely on |
I do not know if this makes sense. If we leave out usual middleware boilerplate what you need is func AllowContentType(contentTypes ...string) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
mediaType, _, err := mime.ParseMediaType(c.Request().Header.Get("Content-Type"))
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, "invalid content-type value")
}
if slices.Contains(contentTypes, mediaType) {
return next(c)
}
return echo.NewHTTPError(http.StatusUnsupportedMediaType)
}
}
} so it is only It is not maybe that complex use case to build middleware for it. Full example: /*
curl --location 'http://localhost:8080/example' -d 'name=test'
*/
func main() {
e := echo.New()
e.Use(middleware.Logger())
e.Use(middleware.Recover())
e.Use(AllowContentType("application/x-www-form-urlencoded"))
e.POST("/example", func(c echo.Context) error {
return c.String(http.StatusOK, c.Path())
})
if err := e.Start(":8080"); err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Fatal(err)
}
}
func AllowContentType(contentTypes ...string) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
mediaType, _, err := mime.ParseMediaType(c.Request().Header.Get("Content-Type"))
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, "invalid content-type value")
}
if slices.Contains(contentTypes, mediaType) {
return next(c)
}
return echo.NewHTTPError(http.StatusUnsupportedMediaType)
}
}
} |
I opened a PR #2655 |
Add an AllowContentType middleware
Checklist
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
Version/commit
The text was updated successfully, but these errors were encountered: