Commit: Bulk unfinished work
This commit is contained in:
29
interceptors/db.go
Normal file
29
interceptors/db.go
Normal file
@@ -0,0 +1,29 @@
|
||||
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)
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user