traefik/old/middlewares/empty_backend_handler.go

31 lines
993 B
Go
Raw Normal View History

2017-07-10 10:11:44 +00:00
package middlewares
import (
"net/http"
2019-03-15 08:42:03 +00:00
"github.com/containous/traefik/pkg/healthcheck"
2017-07-10 10:11:44 +00:00
)
// EmptyBackendHandler is a middlware 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 EmptyBackendHandler struct {
2018-06-11 09:36:03 +00:00
next healthcheck.BalancerHandler
2017-07-10 10:11:44 +00:00
}
// NewEmptyBackendHandler creates a new EmptyBackendHandler instance.
2018-06-11 09:36:03 +00:00
func NewEmptyBackendHandler(lb healthcheck.BalancerHandler) *EmptyBackendHandler {
return &EmptyBackendHandler{next: lb}
2017-07-10 10:11:44 +00:00
}
// ServeHTTP responds with 503 when there is no active Server and otherwise
// invokes the next handler in the middleware chain.
func (h *EmptyBackendHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
2018-06-11 09:36:03 +00:00
if len(h.next.Servers()) == 0 {
2017-07-10 10:11:44 +00:00
rw.WriteHeader(http.StatusServiceUnavailable)
rw.Write([]byte(http.StatusText(http.StatusServiceUnavailable)))
} else {
h.next.ServeHTTP(rw, r)
}
}