forked from mtusi2026/mtusi2026lab2
42 lines
758 B
Go
42 lines
758 B
Go
package middleware
|
|
|
|
import (
|
|
"net/http"
|
|
|
|
"mtusi2026-messenger/internal/dto"
|
|
"mtusi2026-messenger/internal/httpx"
|
|
)
|
|
|
|
func ConcurrencyLimit(max int) func(http.Handler) http.Handler {
|
|
if max <= 0 {
|
|
return func(next http.Handler) http.Handler {
|
|
return next
|
|
}
|
|
}
|
|
|
|
slots := make(chan struct{}, max)
|
|
|
|
return func(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
select {
|
|
case slots <- struct{}{}:
|
|
defer func() {
|
|
<-slots
|
|
}()
|
|
|
|
next.ServeHTTP(w, r)
|
|
|
|
default:
|
|
w.Header().Set("Retry-After", "1")
|
|
httpx.WriteError(
|
|
w,
|
|
http.StatusTooManyRequests,
|
|
dto.ErrorCodeRateLimited,
|
|
"too many requests",
|
|
GetRequestID(r.Context()),
|
|
)
|
|
}
|
|
})
|
|
}
|
|
}
|