context.go

 1package web
 2
 3import (
 4	"context"
 5	"net/http"
 6
 7	"github.com/charmbracelet/log"
 8	"github.com/charmbracelet/soft-serve/server/backend"
 9	"github.com/charmbracelet/soft-serve/server/config"
10	"github.com/charmbracelet/soft-serve/server/db"
11	"github.com/charmbracelet/soft-serve/server/store"
12)
13
14// NewContextMiddleware returns a new context middleware.
15// This middleware adds the config, backend, and logger to the request context.
16func NewContextMiddleware(ctx context.Context) func(http.Handler) http.Handler {
17	cfg := config.FromContext(ctx)
18	be := backend.FromContext(ctx)
19	logger := log.FromContext(ctx).WithPrefix("http")
20	dbx := db.FromContext(ctx)
21	datastore := store.FromContext(ctx)
22	return func(next http.Handler) http.Handler {
23		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
24			ctx := r.Context()
25			ctx = config.WithContext(ctx, cfg)
26			ctx = backend.WithContext(ctx, be)
27			ctx = log.WithContext(ctx, logger)
28			ctx = db.WithContext(ctx, dbx)
29			ctx = store.WithContext(ctx, datastore)
30			r = r.WithContext(ctx)
31			next.ServeHTTP(w, r)
32		})
33	}
34}