goext/ginext/funcWrapper.go

61 lines
1.3 KiB
Go
Raw Permalink Normal View History

2023-07-18 14:40:10 +02:00
package ginext
import (
"fmt"
"github.com/gin-gonic/gin"
2023-07-24 11:11:15 +02:00
"gogs.mikescher.com/BlackForestBytes/goext/exerr"
2023-07-18 14:40:10 +02:00
)
2023-07-18 15:12:06 +02:00
type WHandlerFunc func(PreContext) HTTPResponse
2023-07-18 14:40:10 +02:00
func Wrap(w *GinWrapper, fn WHandlerFunc) gin.HandlerFunc {
return func(g *gin.Context) {
reqctx := g.Request.Context()
2023-12-02 13:07:36 +01:00
pctx := PreContext{
wrapper: w,
ginCtx: g,
persistantData: &preContextData{},
}
for _, lstr := range w.listenerBeforeRequest {
lstr(g)
}
2023-12-02 13:07:36 +01:00
wrap, stackTrace, panicObj := callPanicSafe(fn, pctx)
2023-07-18 14:40:10 +02:00
if panicObj != nil {
2023-07-24 11:11:15 +02:00
2023-07-18 14:40:10 +02:00
fmt.Printf("\n======== ======== STACKTRACE ======== ========\n%s\n======== ======== ======== ========\n\n", stackTrace)
2023-07-24 11:11:15 +02:00
err := exerr.
New(exerr.TypePanic, "Panic occured (in gin handler)").
Any("panicObj", panicObj).
2023-07-18 14:40:10 +02:00
Str("trace", stackTrace).
2023-07-24 11:11:15 +02:00
Build()
wrap = Error(err)
2023-07-18 14:40:10 +02:00
}
if g.Writer.Written() {
panic("Writing in WrapperFunc is not supported")
}
2023-12-02 13:07:36 +01:00
if pctx.persistantData.sessionObj != nil {
2023-12-02 13:38:17 +01:00
err := pctx.persistantData.sessionObj.Finish(reqctx, wrap)
2023-12-02 13:07:36 +01:00
if err != nil {
wrap = Error(exerr.Wrap(err, "Failed to finish session").Any("originalResponse", wrap).Build())
}
}
for _, lstr := range w.listenerAfterRequest {
lstr(g, wrap)
}
2023-07-18 14:40:10 +02:00
if reqctx.Err() == nil {
wrap.Write(g)
}
}
}