2016-05-01 05:08:06 +02:00
|
|
|
package middleware
|
|
|
|
|
|
|
|
import (
|
2016-05-23 20:23:15 +02:00
|
|
|
"bytes"
|
2016-05-01 05:08:06 +02:00
|
|
|
"io/ioutil"
|
|
|
|
"net/http"
|
2016-09-23 07:53:44 +02:00
|
|
|
"net/http/httptest"
|
2016-05-01 05:08:06 +02:00
|
|
|
"testing"
|
|
|
|
|
|
|
|
"github.com/labstack/echo"
|
|
|
|
"github.com/stretchr/testify/assert"
|
|
|
|
)
|
|
|
|
|
|
|
|
func TestBodyLimit(t *testing.T) {
|
|
|
|
e := echo.New()
|
2016-05-23 20:23:15 +02:00
|
|
|
hw := []byte("Hello, World!")
|
2016-09-23 07:53:44 +02:00
|
|
|
req, _ := http.NewRequest(echo.POST, "/", bytes.NewReader(hw))
|
|
|
|
rec := httptest.NewRecorder()
|
2016-05-01 05:08:06 +02:00
|
|
|
c := e.NewContext(req, rec)
|
|
|
|
h := func(c echo.Context) error {
|
2016-09-23 07:53:44 +02:00
|
|
|
body, err := ioutil.ReadAll(c.Request().Body)
|
2016-05-01 06:56:35 +02:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2016-05-01 05:08:06 +02:00
|
|
|
return c.String(http.StatusOK, string(body))
|
|
|
|
}
|
|
|
|
|
2016-05-23 20:23:15 +02:00
|
|
|
// Based on content length (within limit)
|
|
|
|
if assert.NoError(t, BodyLimit("2M")(h)(c)) {
|
2016-09-23 07:53:44 +02:00
|
|
|
assert.Equal(t, http.StatusOK, rec.Code)
|
2016-09-23 08:01:46 +02:00
|
|
|
assert.Equal(t, hw, rec.Body.Bytes())
|
2016-05-23 20:23:15 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// Based on content read (overlimit)
|
|
|
|
he := BodyLimit("2B")(h)(c).(*echo.HTTPError)
|
|
|
|
assert.Equal(t, http.StatusRequestEntityTooLarge, he.Code)
|
|
|
|
|
|
|
|
// Based on content read (within limit)
|
2016-09-23 07:53:44 +02:00
|
|
|
req, _ = http.NewRequest(echo.POST, "/", bytes.NewReader(hw))
|
|
|
|
rec = httptest.NewRecorder()
|
2016-05-23 20:23:15 +02:00
|
|
|
c = e.NewContext(req, rec)
|
|
|
|
if assert.NoError(t, BodyLimit("2M")(h)(c)) {
|
2016-09-23 07:53:44 +02:00
|
|
|
assert.Equal(t, http.StatusOK, rec.Code)
|
2016-05-23 20:23:15 +02:00
|
|
|
assert.Equal(t, "Hello, World!", rec.Body.String())
|
|
|
|
}
|
2016-05-01 05:08:06 +02:00
|
|
|
|
2016-05-23 20:23:15 +02:00
|
|
|
// Based on content read (overlimit)
|
2016-09-23 07:53:44 +02:00
|
|
|
req, _ = http.NewRequest(echo.POST, "/", bytes.NewReader(hw))
|
|
|
|
rec = httptest.NewRecorder()
|
2016-05-01 06:56:35 +02:00
|
|
|
c = e.NewContext(req, rec)
|
2016-05-23 20:23:15 +02:00
|
|
|
he = BodyLimit("2B")(h)(c).(*echo.HTTPError)
|
|
|
|
assert.Equal(t, http.StatusRequestEntityTooLarge, he.Code)
|
2016-05-01 05:08:06 +02:00
|
|
|
}
|