special case handling: if one file has been sent and it is empty, return a correct invalid HTTP code AND remove the resource folder

This commit is contained in:
Julien Neuhart
2019-08-19 16:29:58 +02:00
parent 49ac5e647f
commit cf5e530ed9
2 changed files with 65 additions and 46 deletions

View File

@@ -34,9 +34,10 @@ func contextMiddleware(config conf.Config, processes ...pm2.Process) echo.Middle
// if the endpoint is not for healthcheck, create a
// Resource.
if err := ctx.WithResource(trace); err != nil {
// required to have a correct status code.
ctx.Error(err)
err = doCleanup(ctx, err)
err = doErr(ctx, err)
return ctx.LogRequestResult(err, false)
}
return next(ctx)
}
@@ -62,9 +63,30 @@ func loggerMiddleware() echo.MiddlewareFunc {
func cleanupMiddleware() echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
const op string = "xhttp.cleanupMiddleware"
err := next(c)
ctx := context.MustCastFromEchoContext(c)
return doCleanup(ctx, err)
}
}
}
// errorMiddleware handles errors (if any).
func errorMiddleware() echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
ctx := context.MustCastFromEchoContext(c)
err := next(ctx)
if err == nil {
// so far so good!
return nil
}
return doErr(ctx, err)
}
}
}
func doCleanup(ctx context.Context, err error) error {
const op string = "xhttp.cleanup"
if !ctx.HasResource() {
// nothing to remove.
return err
@@ -84,19 +106,8 @@ func cleanupMiddleware() echo.MiddlewareFunc {
}
return err
}
}
}
// errorMiddleware handles errors (if any).
func errorMiddleware() echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
ctx := context.MustCastFromEchoContext(c)
err := next(ctx)
if err == nil {
// so far so good!
return nil
}
func doErr(ctx context.Context, err error) error {
// if it's an error from echo
// like 404 not found and so on.
if echoHTTPErr, ok := err.(*echo.HTTPError); ok {
@@ -123,5 +134,3 @@ func errorMiddleware() echo.MiddlewareFunc {
ctx.Error(httpErr)
return httpErr
}
}
}

View File

@@ -2,9 +2,11 @@ package context
import (
"fmt"
"io"
"net/http"
"reflect"
"strconv"
"strings"
"time"
"github.com/labstack/echo/v4"
@@ -102,6 +104,14 @@ func (ctx *Context) WithResource(directoryName string) error {
// write form files from request.
form, err := ctx.MultipartForm()
if err != nil {
/*
(very) special case: one and
only one file has been sent
and it is empty.
*/
if strings.Contains(err.Error(), io.EOF.Error()) {
return r, xerror.Invalid(op, "one file has been sent but it is empty: does it exist?", err)
}
return r, err
}
for _, files := range form.File {