aboutsummaryrefslogtreecommitdiff
path: root/backend/router.go
diff options
context:
space:
mode:
authorAnhgelus Morhtuuzh <william@herges.fr>2025-12-22 18:51:42 +0100
committerAnhgelus Morhtuuzh <william@herges.fr>2025-12-22 18:51:42 +0100
commit9ad7b0e67c90697893f188323a32590fbecd5a65 (patch)
tree41c8684a652e8fc5dbedb07bdde6404df4afb628 /backend/router.go
parentcbd5c09c5e1403709d4aabf91051443f147689e5 (diff)
fix(storage): does not store stats if request fails
Diffstat (limited to 'backend/router.go')
-rw-r--r--backend/router.go43
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)
+}