Files
mtusi2026lab4/internal/httpapi/middleware.go
T
2026-10-28 14:12:41 +03:00

42 lines
1.0 KiB
Go

package httpapi
import (
"log"
"net/http"
"time"
"mtusi2026/internal/store"
)
type statusRecorder struct {
http.ResponseWriter
status int
}
func (r *statusRecorder) WriteHeader(status int) {
r.status = status
r.ResponseWriter.WriteHeader(status)
}
func loggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
rec := &statusRecorder{ResponseWriter: w, status: http.StatusOK}
next.ServeHTTP(rec, r)
log.Printf("method=%s path=%s status=%d duration=%s",
r.Method, r.URL.Path, rec.status, time.Since(start))
})
}
func concurrencyMiddleware(limiter *store.Limiter, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !limiter.TryAcquire() {
requestID := newRequestID()
writeError(w, http.StatusServiceUnavailable, requestID, codeUnavailable, "сервер перегружен, попробуйте позже")
return
}
defer limiter.Release()
next.ServeHTTP(w, r)
})
}