2024-03-09 11:21:24 +02:00
|
|
|
// SPDX-License-Identifier: MIT
|
|
|
|
// SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors
|
|
|
|
|
2016-04-24 15:07:55 +02:00
|
|
|
package middleware
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"net/http"
|
2016-09-23 07:53:44 +02:00
|
|
|
"net/http/httptest"
|
2016-04-24 15:07:55 +02:00
|
|
|
"testing"
|
|
|
|
|
2019-01-30 12:56:56 +02:00
|
|
|
"github.com/labstack/echo/v4"
|
2016-04-24 15:07:55 +02:00
|
|
|
"github.com/stretchr/testify/assert"
|
|
|
|
)
|
|
|
|
|
2016-04-28 06:08:06 +02:00
|
|
|
func TestMethodOverride(t *testing.T) {
|
2016-04-24 15:07:55 +02:00
|
|
|
e := echo.New()
|
2016-04-28 06:08:06 +02:00
|
|
|
m := MethodOverride()
|
|
|
|
h := func(c echo.Context) error {
|
2016-05-03 17:32:28 +02:00
|
|
|
return c.String(http.StatusOK, "test")
|
2016-04-28 06:08:06 +02:00
|
|
|
}
|
2016-04-24 15:07:55 +02:00
|
|
|
|
|
|
|
// Override with http header
|
2018-10-14 17:16:58 +02:00
|
|
|
req := httptest.NewRequest(http.MethodPost, "/", nil)
|
2016-09-23 07:53:44 +02:00
|
|
|
rec := httptest.NewRecorder()
|
2018-10-14 17:16:58 +02:00
|
|
|
req.Header.Set(echo.HeaderXHTTPMethodOverride, http.MethodDelete)
|
2016-04-28 06:08:06 +02:00
|
|
|
c := e.NewContext(req, rec)
|
|
|
|
m(h)(c)
|
2018-10-14 17:16:58 +02:00
|
|
|
assert.Equal(t, http.MethodDelete, req.Method)
|
2016-04-24 15:07:55 +02:00
|
|
|
|
2016-04-28 06:08:06 +02:00
|
|
|
// Override with form parameter
|
|
|
|
m = MethodOverrideWithConfig(MethodOverrideConfig{Getter: MethodFromForm("_method")})
|
2018-10-14 17:16:58 +02:00
|
|
|
req = httptest.NewRequest(http.MethodPost, "/", bytes.NewReader([]byte("_method="+http.MethodDelete)))
|
2016-09-23 07:53:44 +02:00
|
|
|
rec = httptest.NewRecorder()
|
|
|
|
req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationForm)
|
2016-04-28 06:08:06 +02:00
|
|
|
c = e.NewContext(req, rec)
|
|
|
|
m(h)(c)
|
2018-10-14 17:16:58 +02:00
|
|
|
assert.Equal(t, http.MethodDelete, req.Method)
|
2016-04-24 15:07:55 +02:00
|
|
|
|
2017-02-02 21:50:17 +02:00
|
|
|
// Override with query parameter
|
2016-04-28 06:08:06 +02:00
|
|
|
m = MethodOverrideWithConfig(MethodOverrideConfig{Getter: MethodFromQuery("_method")})
|
2018-10-14 17:16:58 +02:00
|
|
|
req = httptest.NewRequest(http.MethodPost, "/?_method="+http.MethodDelete, nil)
|
2016-09-23 07:53:44 +02:00
|
|
|
rec = httptest.NewRecorder()
|
2016-04-28 06:08:06 +02:00
|
|
|
c = e.NewContext(req, rec)
|
|
|
|
m(h)(c)
|
2018-10-14 17:16:58 +02:00
|
|
|
assert.Equal(t, http.MethodDelete, req.Method)
|
2016-04-28 06:08:06 +02:00
|
|
|
|
|
|
|
// Ignore `GET`
|
2018-10-14 17:16:58 +02:00
|
|
|
req = httptest.NewRequest(http.MethodGet, "/", nil)
|
|
|
|
req.Header.Set(echo.HeaderXHTTPMethodOverride, http.MethodDelete)
|
|
|
|
assert.Equal(t, http.MethodGet, req.Method)
|
2016-04-24 15:07:55 +02:00
|
|
|
}
|