diff options
Diffstat (limited to 'backend/router.go')
| -rw-r--r-- | backend/router.go | 43 |
1 files changed, 23 insertions, 20 deletions
diff --git a/backend/router.go b/backend/router.go index 161433d..1a2f024 100644 --- a/backend/router.go +++ b/backend/router.go @@ -91,28 +91,11 @@ func NewRouter(debug bool, cfg *Config, db *sql.DB, assets fs.FS) *chi.Mux { }) }) // context - setContext := func(ctx context.Context) context.Context { - ctx = context.WithValue(ctx, configKey, cfg) - ctx = context.WithValue(ctx, assetsFSKey, assets) - ctx = context.WithValue(ctx, debugKey, debug) - return context.WithValue(ctx, storage.DBKey, db) - } - r.Use(func(next http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - next.ServeHTTP(w, r.WithContext(setContext(r.Context()))) - }) - }) - // stats r.Use(func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - go func(r *http.Request) { - ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second) - defer cancel() - if err := storage.UpdateStats(setContext(ctx), r, cfg.Domain); err != nil { - slog.Error("updating stats", "error", err) - } - }(r) - next.ServeHTTP(w, r) + next.ServeHTTP(w, r.WithContext( + setContext(r.Context(), cfg, debug, db, assets), + )) }) }) // login @@ -179,3 +162,23 @@ func HandleStaticFiles(r *chi.Mux, path string, root fs.FS) { http.StripPrefix(pathPrefix, http.FileServerFS(root)).ServeHTTP(w, req) }) } + +func UpdateStats(r *http.Request) { + ctx := r.Context() + cfg := ctx.Value(configKey).(*Config) + debug := ctx.Value(debugKey).(bool) + db := ctx.Value(storage.DBKey).(*sql.DB) + assets := ctx.Value(assetsFSKey).(fs.FS) + + ctx2, cancel := context.WithTimeout(context.Background(), 1*time.Second) + defer cancel() + if err := storage.UpdateStats(setContext(ctx2, cfg, debug, db, assets), r, cfg.Domain); err != nil { + slog.Error("updating stats", "error", err) + } +} +func setContext(ctx context.Context, cfg *Config, debug bool, db *sql.DB, assets fs.FS) context.Context { + ctx = context.WithValue(ctx, configKey, cfg) + ctx = context.WithValue(ctx, assetsFSKey, assets) + ctx = context.WithValue(ctx, debugKey, debug) + return context.WithValue(ctx, storage.DBKey, db) +} |
