Skip to content

Instantly share code, notes, and snippets.

@idoqo
Created July 24, 2020 16:48
Show Gist options
  • Save idoqo/9df064fa9fe956f8d61786361e79bec2 to your computer and use it in GitHub Desktop.
Save idoqo/9df064fa9fe956f8d61786361e79bec2 to your computer and use it in GitHub Desktop.
Middleware to send a database instance as chi middleware
func dbContext(db database.Database) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := context.WithValue(r.Context(), databaseKey, db)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
}
/* USAGE*/
router.Use(dbContext(db))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment