A database/middleware.go => database/middleware.go +19 -0
@@ 0,0 1,19 @@
+package database
+
+import (
+ "github.com/labstack/echo/v4"
+)
+
+// DBTransactionMiddleware will commit a transaction at the end of a request cycle
+// Should be placed as high up in the cycle as possible.
+func DBTransactionMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
+ return func(c echo.Context) error {
+ res := next(c)
+ db := DBFromContext(c.Request().Context())
+ db.EnableCommit()
+ if err := db.CommitTx(); err != nil {
+ return err
+ }
+ return res
+ }
+}
M server/server.go => server/server.go +6 -5
@@ 67,7 67,6 @@ type Server struct {
type Context struct {
echo.Context
Server *Server
- DB database.DBI
User gobwebs.User
}
@@ 285,13 284,15 @@ func (s *Server) WithDefaultMiddleware() *Server {
if s.Session == nil {
panic(fmt.Errorf("You must call Initialize before WithDefaultMiddleware"))
}
- //s.e.Pre(middleware.RemoveTrailingSlashWithConfig(middleware.TrailingSlashConfig{
- // RedirectCode: http.StatusMovedPermanently,
- //}))
// Set custom context
s.e.Use(func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
- ctx := &Context{Context: c, Server: s, DB: database.NewDB(s.DB)}
+ ctx := &Context{Context: c, Server: s}
+ c.SetRequest(
+ c.Request().WithContext(
+ database.Context(c.Request().Context(), database.NewDB(s.DB)),
+ ),
+ )
return next(ctx)
}
})