2015-09-19 11:02:59 +00:00
|
|
|
package middlewares
|
2015-09-24 12:32:37 +00:00
|
|
|
|
2015-09-19 11:02:59 +00:00
|
|
|
import (
|
2015-09-24 12:32:37 +00:00
|
|
|
"net/http"
|
2015-09-24 15:16:13 +00:00
|
|
|
|
2018-01-10 16:48:04 +00:00
|
|
|
"github.com/containous/traefik/middlewares/tracing"
|
2016-06-15 17:07:33 +00:00
|
|
|
"github.com/vulcand/oxy/cbreaker"
|
2015-09-19 11:02:59 +00:00
|
|
|
)
|
|
|
|
|
2015-11-01 18:34:54 +00:00
|
|
|
// CircuitBreaker holds the oxy circuit breaker.
|
2015-09-19 11:02:59 +00:00
|
|
|
type CircuitBreaker struct {
|
|
|
|
circuitBreaker *cbreaker.CircuitBreaker
|
|
|
|
}
|
|
|
|
|
2015-11-01 18:34:54 +00:00
|
|
|
// NewCircuitBreaker returns a new CircuitBreaker.
|
2016-06-22 20:14:40 +00:00
|
|
|
func NewCircuitBreaker(next http.Handler, expression string, options ...cbreaker.CircuitBreakerOption) (*CircuitBreaker, error) {
|
|
|
|
circuitBreaker, err := cbreaker.New(next, expression, options...)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return &CircuitBreaker{circuitBreaker}, nil
|
2015-09-19 11:02:59 +00:00
|
|
|
}
|
|
|
|
|
2018-01-10 16:48:04 +00:00
|
|
|
// NewCircuitBreakerOptions returns a new CircuitBreakerOption
|
|
|
|
func NewCircuitBreakerOptions(expression string) cbreaker.CircuitBreakerOption {
|
|
|
|
return cbreaker.Fallback(
|
|
|
|
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
tracing.LogEventf(r, "blocked by circuitbreaker (%q)", expression)
|
|
|
|
w.WriteHeader(http.StatusServiceUnavailable)
|
|
|
|
w.Write([]byte(http.StatusText(http.StatusServiceUnavailable)))
|
|
|
|
}))
|
|
|
|
}
|
|
|
|
|
2015-09-19 11:02:59 +00:00
|
|
|
func (cb *CircuitBreaker) ServeHTTP(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
|
|
|
|
cb.circuitBreaker.ServeHTTP(rw, r)
|
|
|
|
}
|