Documentation
¶
Overview ¶
Package txctx is a Fiber v2 + GORM middleware that manages a request-scoped database transaction. See txctxv3 for the Fiber v3 variant.
Index ¶
- func BoolPtr(v bool) *bool
- func DB(c *fiber.Ctx) *gorm.DB
- func DBFromCtx(ctx context.Context) *gorm.DB
- func Middleware(db *gorm.DB, cfg Config, extractor ...ContextExtractor) fiber.Handler
- func OnCommit(c *fiber.Ctx, fn func(*gorm.DB) error)
- func OnCommitCtx(ctx context.Context, fn func(*gorm.DB) error)
- func OnRollback(c *fiber.Ctx, fn func(*gorm.DB) error)
- func OnRollbackCtx(ctx context.Context, fn func(*gorm.DB) error)
- func Outside(c *fiber.Ctx) *gorm.DB
- func OutsideCtx(ctx context.Context) *gorm.DB
- type Config
- type ContextExtractor
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func DB ¶
DB returns the request-scoped *gorm.DB. With LazyTx the first write call transparently opens BEGIN; reads stay outside any transaction.
func Middleware ¶
Middleware returns a Fiber v2 middleware that manages a request-scoped GORM transaction with timeout-triggered rollback and commit/rollback callbacks. An optional ContextExtractor may be supplied to override the base context (default: c.UserContext()).
func OnCommit ¶
OnCommit registers fn to run only if the transaction commits successfully. Callbacks run in registration order; the first error stops the chain and is reported via Config.OnCallbackError (the commit itself is not undone).
func OnCommitCtx ¶
OnCommitCtx is the context.Context variant of OnCommit.
func OnRollback ¶
OnRollback registers fn to run if the transaction rolls back.
func OnRollbackCtx ¶
OnRollbackCtx is the context.Context variant of OnRollback.
Types ¶
type ContextExtractor ¶ added in v0.7.0
ContextExtractor is called once per request to obtain the base context for the transaction holder. When provided to Middleware it is used instead of c.UserContext().
When to use it: Elastic APM stores its transaction on the fasthttp RequestCtx (accessible via c.Context()), while Fiber keeps its own stdlib context on c.UserContext(). Without an extractor, GORM callbacks that call apmgorm.WithContext lose the APM transaction. Supply an extractor whenever apmfiber.Middleware is in the chain.
Correct 3-middleware ordering:
app.Use(apmfiber.Middleware()) // 1. captures APM tx on RequestCtx app.Use(logfiber.Middleware()) // 2. reads APM tx for trace fields app.Use(txctx.Middleware(db, cfg, extractor)) // 3. inherits APM ctx
Example extractor for Fiber v2 (pulls the fasthttp RequestCtx which carries the APM transaction set by apmfiber.Middleware):
func(c *fiber.Ctx) context.Context { return (*c).UserContext() }
To forward the APM-enriched fasthttp context into GORM, use:
func(c *fiber.Ctx) context.Context { return c.Context() }