context.go

 1package web
 2
 3import (
 4	"context"
 5	"net/http"
 6
 7	"github.com/charmbracelet/log"
 8	"github.com/charmbracelet/soft-serve/pkg/backend"
 9	"github.com/charmbracelet/soft-serve/pkg/config"
10	"github.com/charmbracelet/soft-serve/pkg/db"
11	"github.com/charmbracelet/soft-serve/pkg/store"
12)
13
14// NewContextHandler returns a new context middleware.
15// This middleware adds the config, backend, and logger to the request context.
16func NewContextHandler(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.With(
28				"method", r.Method,
29				"path", r.URL,
30				"addr", r.RemoteAddr,
31			))
32			ctx = db.WithContext(ctx, dbx)
33			ctx = store.WithContext(ctx, datastore)
34			r = r.WithContext(ctx)
35			next.ServeHTTP(w, r)
36		})
37	}
38}