forked from mtusi2026/mtusi2026lab3
49 lines
1.1 KiB
Go
49 lines
1.1 KiB
Go
package middleware
|
|
|
|
import (
|
|
"net/http"
|
|
"sync/atomic"
|
|
|
|
"mtusi2026lab3/internal/transport/http/response"
|
|
)
|
|
|
|
// AvailabilityGate lets a process reject new work before its HTTP listener is
|
|
// closed. Existing requests are still drained by http.Server.Shutdown.
|
|
type AvailabilityGate struct {
|
|
accepting atomic.Bool
|
|
}
|
|
|
|
func NewAvailabilityGate() *AvailabilityGate {
|
|
gate := &AvailabilityGate{}
|
|
gate.accepting.Store(true)
|
|
|
|
return gate
|
|
}
|
|
|
|
func (g *AvailabilityGate) BeginDrain() {
|
|
g.accepting.Store(false)
|
|
}
|
|
|
|
func (g *AvailabilityGate) IsAccepting() bool {
|
|
return g.accepting.Load()
|
|
}
|
|
|
|
func (g *AvailabilityGate) Middleware(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
// Liveness deliberately stays available while the process drains. The
|
|
// readiness endpoint and all business traffic receive 503 immediately.
|
|
if g.IsAccepting() || r.URL.Path == "/health/live" {
|
|
next.ServeHTTP(w, r)
|
|
return
|
|
}
|
|
|
|
response.WriteError(
|
|
w,
|
|
http.StatusServiceUnavailable,
|
|
response.CodeUnavailable,
|
|
"service is draining",
|
|
GetRequestID(r.Context()),
|
|
)
|
|
})
|
|
}
|