database: add middleware

This commit is contained in:
Drew DeVault 2022-07-09 13:52:55 +02:00
parent 208f766963
commit b5656c9a1e
2 changed files with 22 additions and 6 deletions

View file

@ -6,12 +6,6 @@ import (
"errors"
)
var dbCtxKey = &contextKey{"database"}
type contextKey struct {
name string
}
func Context(ctx context.Context, db *sql.DB) context.Context {
return context.WithValue(ctx, dbCtxKey, db)
}

22
database/middleware.go Normal file
View 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)
})
}
}