2018-11-14 09:18:03 +00:00
|
|
|
package emptybackendhandler
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
|
|
|
|
2020-09-16 13:46:04 +00:00
|
|
|
"github.com/traefik/traefik/v2/pkg/healthcheck"
|
2018-11-14 09:18:03 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// EmptyBackend is a middleware that checks whether the current Backend
|
|
|
|
// has at least one active Server in respect to the healthchecks and if this
|
|
|
|
// is not the case, it will stop the middleware chain and respond with 503.
|
|
|
|
type emptyBackend struct {
|
2021-06-25 19:08:11 +00:00
|
|
|
healthcheck.BalancerStatusHandler
|
2018-11-14 09:18:03 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// New creates a new EmptyBackend middleware.
|
2021-06-25 19:08:11 +00:00
|
|
|
func New(lb healthcheck.BalancerStatusHandler) http.Handler {
|
|
|
|
return &emptyBackend{BalancerStatusHandler: lb}
|
2018-11-14 09:18:03 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// ServeHTTP responds with 503 when there is no active Server and otherwise
|
|
|
|
// invokes the next handler in the middleware chain.
|
|
|
|
func (e *emptyBackend) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
|
2021-06-25 19:08:11 +00:00
|
|
|
if len(e.BalancerStatusHandler.Servers()) != 0 {
|
|
|
|
e.BalancerStatusHandler.ServeHTTP(rw, req)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
rw.WriteHeader(http.StatusServiceUnavailable)
|
|
|
|
if _, err := rw.Write([]byte(http.StatusText(http.StatusServiceUnavailable))); err != nil {
|
|
|
|
http.Error(rw, err.Error(), http.StatusInternalServerError)
|
|
|
|
return
|
2018-11-14 09:18:03 +00:00
|
|
|
}
|
|
|
|
}
|