Files
vt/interceptors/db.go
2026-01-22 17:39:04 +01:00

30 lines
622 B
Go

package interceptors
import (
"context"
"net/http"
"gorm.io/gorm"
)
var dbKey key
func NewDBContext(ctx context.Context, db *gorm.DB) context.Context {
return context.WithValue(ctx, dbKey, db)
}
// FromContext returns the User value stored in ctx, if any.
func DBFromContex(ctx context.Context) (*gorm.DB, bool) {
u, ok := ctx.Value(dbKey).(*gorm.DB)
return u, ok
}
func AddDBToContext(next http.Handler, db *gorm.DB) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
ctx = NewDBContext(ctx, db)
r = r.WithContext(ctx)
next.ServeHTTP(w, r)
})
}