v0.0.220 add ginext.bufferBody

This commit is contained in:
2023-08-03 09:09:27 +02:00
parent 2f1b784dc2
commit 9136143f2f
6 changed files with 41 additions and 6 deletions

View File

@@ -0,0 +1,14 @@
package ginext
import (
"github.com/gin-gonic/gin"
"gogs.mikescher.com/BlackForestBytes/goext/dataext"
)
func BodyBuffer() gin.HandlerFunc {
return func(g *gin.Context) {
if g.Request.Body != nil {
g.Request.Body = dataext.NewBufferedReadCloser(g.Request.Body)
}
}
}

View File

@@ -18,6 +18,7 @@ type GinWrapper struct {
allowCors bool
ginDebug bool
bufferBody bool
requestTimeout time.Duration
routeSpecs []ginRouteSpec
@@ -30,7 +31,13 @@ type ginRouteSpec struct {
Handler string
}
func NewEngine(allowCors bool, ginDebug bool, timeout time.Duration) *GinWrapper {
// NewEngine creates a new (wrapped) ginEngine
// Parameters are:
// - [allowCors] Add cors handler to allow all CORS requests on the default http methods
// - [ginDebug] Set gin.debug to true (adds more logs)
// - [bufferBody] Buffers the input body stream, this way the ginext error handler can later include the whole request body
// - [timeout] The default handler timeout
func NewEngine(allowCors bool, ginDebug bool, bufferBody bool, timeout time.Duration) *GinWrapper {
engine := gin.New()
wrapper := &GinWrapper{
@@ -38,6 +45,7 @@ func NewEngine(allowCors bool, ginDebug bool, timeout time.Duration) *GinWrapper
SuppressGinLogs: false,
allowCors: allowCors,
ginDebug: ginDebug,
bufferBody: bufferBody,
requestTimeout: timeout,
}

View File

@@ -111,6 +111,13 @@ func (w *GinRouteBuilder) Use(middleware ...gin.HandlerFunc) *GinRouteBuilder {
func (w *GinRouteBuilder) Handle(handler WHandlerFunc) {
if w.routes.wrapper.bufferBody {
arr := make([]gin.HandlerFunc, len(w.handlers)+1)
arr = append(arr, BodyBuffer())
arr = append(arr, w.handlers...)
w.handlers = arr
}
middlewareNames := langext.ArrMap(w.handlers, func(v gin.HandlerFunc) string { return nameOfFunction(v) })
handlerName := nameOfFunction(handler)