From 9ad7b0e67c90697893f188323a32590fbecd5a65 Mon Sep 17 00:00:00 2001 From: Anhgelus Morhtuuzh Date: Mon, 22 Dec 2025 18:51:42 +0100 Subject: fix(storage): does not store stats if request fails --- backend/router.go | 43 +++++++++++++++++++++++-------------------- 1 file changed, 23 insertions(+), 20 deletions(-) (limited to 'backend/router.go') 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) +} -- cgit v1.2.3