package api import ( "net/http" "time" "marketing-system-data-tool/server/internal/logging" ) type statusWriter struct{ http.ResponseWriter status int bytes int } func (w *statusWriter) WriteHeader(code int){ w.status = code w.ResponseWriter.WriteHeader(code) } func (w *statusWriter) Write(b []byte)(int, error){ n, err := w.ResponseWriter.Write(b) w.bytes += n return n, err } func withAccess(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request){ w.Header().Set("Access-Control-Allow-Origin", "*") w.Header().Set("Access-Control-Allow-Methods", "GET,POST,PATCH,DELETE,OPTIONS") w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization") if r.Method == http.MethodOptions { w.WriteHeader(http.StatusOK) return } start := time.Now() sw := &statusWriter{ResponseWriter: w, status: 200} h.ServeHTTP(sw, r) dur := time.Since(start) m := MetaFrom(r) logging.JSON("INFO", map[string]interface{}{ "kind": "access", "trace_id": TraceIDFrom(r), "method": m.Method, "path": m.Path, "query": m.Query, "remote": m.Remote, "status": sw.status, "bytes": sw.bytes, "duration_ms": dur.Milliseconds(), }) }) }