linstrom/server/middlewares/injectStorage.go

23 lines
624 B
Go
Raw Normal View History

2024-05-31 09:54:39 +00:00
package middlewares
import (
"context"
"net/http"
"gitlab.com/mstarongitlab/linstrom/storage"
)
const CONTEXT_KEY_STORAGE = ContextKey("storage")
// Build a middleware for injecting a storage reference into the context
func InjectStorageMiddlewareBuilder(store *storage.Storage) func(http.Handler) http.Handler {
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
reqContext := r.Context()
newContext := context.WithValue(reqContext, CONTEXT_KEY_STORAGE, store)
newRequest := r.WithContext(newContext)
h.ServeHTTP(w, newRequest)
})
}
}