mirror of
https://github.com/hanzoai/gateway.git
synced 2026-10-30 15:04:44 +00:00
Modules declare go 1.27.1 and the build images follow. go fix applied the modernizers; omitzero is not applied, since it changes what the JSON says. Co-authored-by: Hanzo Dev <[email protected]>
65 lines
1.8 KiB
Go
65 lines
1.8 KiB
Go
/*
|
|
Package gobreaker provides a circuit breaker proxy middleware using the sony/gobreaker lib.
|
|
|
|
Adding the middleware to your proxy stack
|
|
|
|
import (
|
|
"github.com/hanzoai/gateway/v2/internal/lura/proxy"
|
|
gobreaker "github.com/hanzoai/gateway/v2/internal/plugin/circuitbreaker/gobreaker/proxy"
|
|
)
|
|
|
|
...
|
|
|
|
var p proxy.Proxy
|
|
var backend *config.Backend
|
|
|
|
...
|
|
|
|
p = gobreaker.NewMiddleware(backend)(p)
|
|
|
|
...
|
|
*/
|
|
package proxy
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
|
|
"github.com/hanzoai/gateway/v2/internal/lura/config"
|
|
"github.com/hanzoai/gateway/v2/internal/lura/logging"
|
|
"github.com/hanzoai/gateway/v2/internal/lura/proxy"
|
|
|
|
gcb "github.com/hanzoai/gateway/v2/internal/plugin/circuitbreaker/gobreaker"
|
|
)
|
|
|
|
// BackendFactory adds a cb middleware wrapping the internal factory
|
|
func BackendFactory(next proxy.BackendFactory, logger logging.Logger) proxy.BackendFactory {
|
|
return func(cfg *config.Backend) proxy.Proxy {
|
|
return NewMiddleware(cfg, logger)(next(cfg))
|
|
}
|
|
}
|
|
|
|
// NewMiddleware builds a middleware based on the extra config params or fallbacks to the next proxy
|
|
func NewMiddleware(remote *config.Backend, logger logging.Logger) proxy.Middleware {
|
|
data := gcb.ConfigGetter(remote.ExtraConfig).(gcb.Config)
|
|
if data == gcb.ZeroCfg {
|
|
return proxy.EmptyMiddleware
|
|
}
|
|
cb := gcb.NewCircuitBreaker(data, logger)
|
|
|
|
logger.Debug(fmt.Sprintf("[BACKEND: %s][CB] Creating the circuit breaker named '%s'", remote.URLPattern, data.Name))
|
|
|
|
return func(next ...proxy.Proxy) proxy.Proxy {
|
|
if len(next) > 1 {
|
|
panic(proxy.ErrTooManyProxies)
|
|
}
|
|
return func(ctx context.Context, request *proxy.Request) (*proxy.Response, error) {
|
|
result, err := cb.Execute(func() (any, error) { return next[0](ctx, request) })
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return result.(*proxy.Response), err
|
|
}
|
|
}
|
|
}
|