mirror of
https://github.com/labstack/echo.git
synced 2025-01-07 23:01:56 +02:00
6ef5f77bf2
WIP: make default logger implemented custom writer for jsonlike logs WIP: improve examples WIP: defaultErrorHandler use errors.As to unwrap errors. Update readme WIP: default logger logs json, restore e.Start method WIP: clean router.Match a bit WIP: func types/fields have echo.Context has first element WIP: remove yaml tags as functions etc can not be serialized anyway WIP: change BindPathParams,BindQueryParams,BindHeaders from methods to functions and reverse arguments to be like DefaultBinder.Bind is WIP: improved comments, logger now extracts status from error WIP: go mod tidy WIP: rebase with 4.5.0 WIP: * removed todos. * removed StartAutoTLS and StartH2CServer methods from `StartConfig` * KeyAuth middleware errorhandler can swallow the error and resume next middleware WIP: add RouterConfig.UseEscapedPathForMatching to use escaped path for matching request against routes WIP: FIXMEs WIP: upgrade golang-jwt/jwt to `v4` WIP: refactor http methods to return RouteInfo WIP: refactor static not creating multiple routes WIP: refactor route and middleware adding functions not to return error directly WIP: Use 401 for problematic/missing headers for key auth and JWT middleware (#1552, #1402). > In summary, a 401 Unauthorized response should be used for missing or bad authentication WIP: replace `HTTPError.SetInternal` with `HTTPError.WithInternal` so we could not mutate global error variables WIP: add RouteInfo and RouteMatchType into Context what we could know from in middleware what route was matched and/or type of that match (200/404/405) WIP: make notFoundHandler and methodNotAllowedHandler private. encourage that all errors be handled in Echo.HTTPErrorHandler WIP: server cleanup ideas WIP: routable.ForGroup WIP: note about logger middleware WIP: bind should not default values on second try. use crypto rand for better randomness WIP: router add route as interface and returns info as interface WIP: improve flaky test (remains still flaky) WIP: add notes about bind default values WIP: every route can have their own path params names WIP: routerCreator and different tests WIP: different things WIP: remove route implementation WIP: support custom method types WIP: extractor tests WIP: v5.0.x proposal over v4.4.0
252 lines
6.4 KiB
Go
252 lines
6.4 KiB
Go
package middleware
|
|
|
|
import (
|
|
"bytes"
|
|
"compress/gzip"
|
|
"errors"
|
|
"io/ioutil"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"sync"
|
|
"testing"
|
|
|
|
"github.com/labstack/echo/v4"
|
|
"github.com/stretchr/testify/assert"
|
|
)
|
|
|
|
func TestDecompress(t *testing.T) {
|
|
e := echo.New()
|
|
|
|
h := Decompress()(func(c echo.Context) error {
|
|
c.Response().Write([]byte("test")) // For Content-Type sniffing
|
|
return nil
|
|
})
|
|
|
|
// Decompress request body
|
|
body := `{"name": "echo"}`
|
|
gz, _ := gzipString(body)
|
|
req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(string(gz)))
|
|
req.Header.Set(echo.HeaderContentEncoding, GZIPEncoding)
|
|
rec := httptest.NewRecorder()
|
|
c := e.NewContext(req, rec)
|
|
|
|
err := h(c)
|
|
assert.NoError(t, err)
|
|
|
|
assert.Equal(t, GZIPEncoding, req.Header.Get(echo.HeaderContentEncoding))
|
|
b, err := ioutil.ReadAll(req.Body)
|
|
assert.NoError(t, err)
|
|
assert.Equal(t, body, string(b))
|
|
}
|
|
|
|
func TestDecompress_skippedIfNoHeader(t *testing.T) {
|
|
e := echo.New()
|
|
req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader("test"))
|
|
rec := httptest.NewRecorder()
|
|
c := e.NewContext(req, rec)
|
|
|
|
// Skip if no Content-Encoding header
|
|
h := Decompress()(func(c echo.Context) error {
|
|
c.Response().Write([]byte("test")) // For Content-Type sniffing
|
|
return nil
|
|
})
|
|
|
|
err := h(c)
|
|
assert.NoError(t, err)
|
|
assert.Equal(t, "test", rec.Body.String())
|
|
|
|
}
|
|
|
|
func TestDecompressWithConfig_DefaultConfig_noDecode(t *testing.T) {
|
|
e := echo.New()
|
|
req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader("test"))
|
|
rec := httptest.NewRecorder()
|
|
c := e.NewContext(req, rec)
|
|
|
|
h, err := DecompressConfig{}.ToMiddleware()
|
|
assert.NoError(t, err)
|
|
|
|
err = h(func(c echo.Context) error {
|
|
c.Response().Write([]byte("test")) // For Content-Type sniffing
|
|
return nil
|
|
})(c)
|
|
assert.NoError(t, err)
|
|
|
|
assert.Equal(t, "test", rec.Body.String())
|
|
|
|
}
|
|
|
|
func TestDecompressWithConfig_DefaultConfig(t *testing.T) {
|
|
e := echo.New()
|
|
req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader("test"))
|
|
rec := httptest.NewRecorder()
|
|
c := e.NewContext(req, rec)
|
|
|
|
h := Decompress()(func(c echo.Context) error {
|
|
c.Response().Write([]byte("test")) // For Content-Type sniffing
|
|
return nil
|
|
})
|
|
|
|
// Decompress
|
|
body := `{"name": "echo"}`
|
|
gz, _ := gzipString(body)
|
|
req = httptest.NewRequest(http.MethodPost, "/", strings.NewReader(string(gz)))
|
|
req.Header.Set(echo.HeaderContentEncoding, GZIPEncoding)
|
|
rec = httptest.NewRecorder()
|
|
c = e.NewContext(req, rec)
|
|
|
|
err := h(c)
|
|
assert.NoError(t, err)
|
|
|
|
assert.Equal(t, GZIPEncoding, req.Header.Get(echo.HeaderContentEncoding))
|
|
b, err := ioutil.ReadAll(req.Body)
|
|
assert.NoError(t, err)
|
|
assert.Equal(t, body, string(b))
|
|
}
|
|
|
|
func TestCompressRequestWithoutDecompressMiddleware(t *testing.T) {
|
|
e := echo.New()
|
|
body := `{"name":"echo"}`
|
|
gz, _ := gzipString(body)
|
|
req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(string(gz)))
|
|
req.Header.Set(echo.HeaderContentEncoding, GZIPEncoding)
|
|
rec := httptest.NewRecorder()
|
|
e.NewContext(req, rec)
|
|
|
|
e.ServeHTTP(rec, req)
|
|
|
|
assert.Equal(t, GZIPEncoding, req.Header.Get(echo.HeaderContentEncoding))
|
|
b, err := ioutil.ReadAll(req.Body)
|
|
assert.NoError(t, err)
|
|
assert.NotEqual(t, b, body)
|
|
assert.Equal(t, b, gz)
|
|
}
|
|
|
|
func TestDecompressNoContent(t *testing.T) {
|
|
e := echo.New()
|
|
req := httptest.NewRequest(http.MethodGet, "/", nil)
|
|
req.Header.Set(echo.HeaderContentEncoding, GZIPEncoding)
|
|
rec := httptest.NewRecorder()
|
|
c := e.NewContext(req, rec)
|
|
h := Decompress()(func(c echo.Context) error {
|
|
return c.NoContent(http.StatusNoContent)
|
|
})
|
|
|
|
err := h(c)
|
|
|
|
if assert.NoError(t, err) {
|
|
assert.Equal(t, GZIPEncoding, req.Header.Get(echo.HeaderContentEncoding))
|
|
assert.Empty(t, rec.Header().Get(echo.HeaderContentType))
|
|
assert.Equal(t, 0, len(rec.Body.Bytes()))
|
|
}
|
|
}
|
|
|
|
func TestDecompressErrorReturned(t *testing.T) {
|
|
e := echo.New()
|
|
e.Use(Decompress())
|
|
e.GET("/", func(c echo.Context) error {
|
|
return echo.ErrNotFound
|
|
})
|
|
req := httptest.NewRequest(http.MethodGet, "/", nil)
|
|
req.Header.Set(echo.HeaderContentEncoding, GZIPEncoding)
|
|
rec := httptest.NewRecorder()
|
|
|
|
e.ServeHTTP(rec, req)
|
|
|
|
assert.Equal(t, http.StatusNotFound, rec.Code)
|
|
assert.Empty(t, rec.Header().Get(echo.HeaderContentEncoding))
|
|
}
|
|
|
|
func TestDecompressSkipper(t *testing.T) {
|
|
e := echo.New()
|
|
e.Use(DecompressWithConfig(DecompressConfig{
|
|
Skipper: func(c echo.Context) bool {
|
|
return c.Request().URL.Path == "/skip"
|
|
},
|
|
}))
|
|
body := `{"name": "echo"}`
|
|
req := httptest.NewRequest(http.MethodPost, "/skip", strings.NewReader(body))
|
|
req.Header.Set(echo.HeaderContentEncoding, GZIPEncoding)
|
|
rec := httptest.NewRecorder()
|
|
c := e.NewContext(req, rec)
|
|
|
|
e.ServeHTTP(rec, req)
|
|
|
|
assert.Equal(t, rec.Header().Get(echo.HeaderContentType), echo.MIMEApplicationJSONCharsetUTF8)
|
|
reqBody, err := ioutil.ReadAll(c.Request().Body)
|
|
assert.NoError(t, err)
|
|
assert.Equal(t, body, string(reqBody))
|
|
}
|
|
|
|
type TestDecompressPoolWithError struct {
|
|
}
|
|
|
|
func (d *TestDecompressPoolWithError) gzipDecompressPool() sync.Pool {
|
|
return sync.Pool{
|
|
New: func() interface{} {
|
|
return errors.New("pool error")
|
|
},
|
|
}
|
|
}
|
|
|
|
func TestDecompressPoolError(t *testing.T) {
|
|
e := echo.New()
|
|
e.Use(DecompressWithConfig(DecompressConfig{
|
|
Skipper: DefaultSkipper,
|
|
GzipDecompressPool: &TestDecompressPoolWithError{},
|
|
}))
|
|
body := `{"name": "echo"}`
|
|
req := httptest.NewRequest(http.MethodPost, "/echo", strings.NewReader(body))
|
|
req.Header.Set(echo.HeaderContentEncoding, GZIPEncoding)
|
|
rec := httptest.NewRecorder()
|
|
c := e.NewContext(req, rec)
|
|
|
|
e.ServeHTTP(rec, req)
|
|
|
|
assert.Equal(t, GZIPEncoding, req.Header.Get(echo.HeaderContentEncoding))
|
|
reqBody, err := ioutil.ReadAll(c.Request().Body)
|
|
assert.NoError(t, err)
|
|
assert.Equal(t, body, string(reqBody))
|
|
assert.Equal(t, rec.Code, http.StatusInternalServerError)
|
|
}
|
|
|
|
func BenchmarkDecompress(b *testing.B) {
|
|
e := echo.New()
|
|
body := `{"name": "echo"}`
|
|
gz, _ := gzipString(body)
|
|
req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(string(gz)))
|
|
req.Header.Set(echo.HeaderContentEncoding, GZIPEncoding)
|
|
|
|
h := Decompress()(func(c echo.Context) error {
|
|
c.Response().Write([]byte(body)) // For Content-Type sniffing
|
|
return nil
|
|
})
|
|
|
|
b.ReportAllocs()
|
|
b.ResetTimer()
|
|
|
|
for i := 0; i < b.N; i++ {
|
|
// Decompress
|
|
rec := httptest.NewRecorder()
|
|
c := e.NewContext(req, rec)
|
|
h(c)
|
|
}
|
|
}
|
|
|
|
func gzipString(body string) ([]byte, error) {
|
|
var buf bytes.Buffer
|
|
gz := gzip.NewWriter(&buf)
|
|
|
|
_, err := gz.Write([]byte(body))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
if err := gz.Close(); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return buf.Bytes(), nil
|
|
}
|