Skip to content
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

Allow content type middleware #2655

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions middleware/allow_content_type.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package middleware

import (
"mime"
"net/http"
"slices"

"github.com/labstack/echo/v4"
)

func AllowContentType(contentTypes ...string) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
var acceptTypes = ""
for i, contentType := range contentTypes {
acceptTypes += contentType

if i != len(contentTypes)-1 {
acceptTypes += ","
}
}
c.Response().Header().Set("Accept", acceptTypes)

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)
}
}
}
32 changes: 32 additions & 0 deletions middleware/allow_content_type_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package middleware

import (
"net/http"
"net/http/httptest"
"testing"

"github.com/labstack/echo/v4"
"github.com/stretchr/testify/assert"
)

func TestAllowContentType(t *testing.T) {
e := echo.New()
req := httptest.NewRequest(http.MethodGet, "/", nil)
res := httptest.NewRecorder()

h := AllowContentType("application/json")(func(c echo.Context) error {
return c.String(http.StatusOK, "test")
})

// Test valid content type
req.Header.Add("Content-Type", "application/json")
c := e.NewContext(req, res)
assert.NoError(t, h(c))
assert.Equal(t, "application/json", res.Header().Get("Accept"))

// Test invalid content type
req.Header.Set("Content-Type", "text/plain")
c = e.NewContext(req, res)
he := h(c).(*echo.HTTPError)
assert.Equal(t, http.StatusUnsupportedMediaType, he.Code)
}