database: add middleware
This commit is contained in:
parent
208f766963
commit
b5656c9a1e
2 changed files with 22 additions and 6 deletions
|
@ -6,12 +6,6 @@ import (
|
||||||
"errors"
|
"errors"
|
||||||
)
|
)
|
||||||
|
|
||||||
var dbCtxKey = &contextKey{"database"}
|
|
||||||
|
|
||||||
type contextKey struct {
|
|
||||||
name string
|
|
||||||
}
|
|
||||||
|
|
||||||
func Context(ctx context.Context, db *sql.DB) context.Context {
|
func Context(ctx context.Context, db *sql.DB) context.Context {
|
||||||
return context.WithValue(ctx, dbCtxKey, db)
|
return context.WithValue(ctx, dbCtxKey, db)
|
||||||
}
|
}
|
||||||
|
|
22
database/middleware.go
Normal file
22
database/middleware.go
Normal file
|
@ -0,0 +1,22 @@
|
||||||
|
package database
|
||||||
|
|
||||||
|
import (
|
||||||
|
"database/sql"
|
||||||
|
"net/http"
|
||||||
|
)
|
||||||
|
|
||||||
|
var dbCtxKey = &contextKey{"database"}
|
||||||
|
|
||||||
|
type contextKey struct {
|
||||||
|
name string
|
||||||
|
}
|
||||||
|
|
||||||
|
func Middleware(db *sql.DB) func(http.Handler) http.Handler {
|
||||||
|
return func(next http.Handler) http.Handler {
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
ctx := Context(r.Context(), db)
|
||||||
|
r = r.WithContext(ctx)
|
||||||
|
next.ServeHTTP(w, r)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in a new issue