Files
MyClub/internal/middleware/db_context.go
T
Tomas Dvorak 8762bde4bf dev day #89
2025-11-11 10:29:30 +01:00

38 lines
1.0 KiB
Go

package middleware
import (
"context"
"time"
"github.com/gin-gonic/gin"
)
// DBContext adds a context with timeout to all database operations
// This prevents queries from hanging indefinitely and exhausting connections
func DBContext() gin.HandlerFunc {
return func(c *gin.Context) {
// Create a context with timeout for this request's database operations
// 15 seconds is generous for most queries while preventing indefinite hangs
ctx, cancel := context.WithTimeout(c.Request.Context(), 15*time.Second)
defer cancel()
// Store the context so controllers can use it with db.WithContext(ctx)
c.Set("dbCtx", ctx)
c.Next()
}
}
// GetDBContext retrieves the database context from gin.Context
// Returns a background context with timeout if not found
func GetDBContext(c *gin.Context) context.Context {
if ctx, exists := c.Get("dbCtx"); exists {
if dbCtx, ok := ctx.(context.Context); ok {
return dbCtx
}
}
// Fallback with timeout
ctx, _ := context.WithTimeout(context.Background(), 15*time.Second)
return ctx
}