bouncer/internal/proxy/director/layer_registry.go

112 lines
2.3 KiB
Go
Raw Normal View History

2023-04-24 20:52:12 +02:00
package director
import (
"forge.cadoles.com/Cadoles/go-proxy"
"forge.cadoles.com/cadoles/bouncer/internal/store"
)
type Middleware interface {
Middleware() proxy.Middleware
}
type RequestTransformer interface {
RequestTransformer() proxy.RequestTransformer
}
type ResponseTransformer interface {
ResponseTransformer() proxy.ResponseTransformer
}
type LayerRegistry struct {
index map[store.LayerType]map[string]Layer
}
func (r *LayerRegistry) GetLayer(layerType store.LayerType, name string) (Layer, bool) {
layers, exists := r.index[layerType]
if !exists {
return nil, false
}
layer, exists := layers[name]
if !exists {
return nil, false
}
return layer, true
}
func (r *LayerRegistry) getLayerAsAny(layerType store.LayerType, name string) (any, bool) {
return r.GetLayer(layerType, name)
}
func (r *LayerRegistry) GetMiddleware(layerType store.LayerType, name string) (proxy.Middleware, bool) {
layer, exists := r.getLayerAsAny(layerType, name)
if !exists {
return nil, false
}
middleware, ok := layer.(proxy.Middleware)
if !ok {
return nil, false
}
return middleware, true
}
func (r *LayerRegistry) GetResponseTransformer(layerType store.LayerType, name string) (proxy.ResponseTransformer, bool) {
layer, exists := r.getLayerAsAny(layerType, name)
if !exists {
return nil, false
}
transformer, ok := layer.(proxy.ResponseTransformer)
if !ok {
return nil, false
}
return transformer, true
}
func (r *LayerRegistry) GetRequestTransformer(layerType store.LayerType, name string) (proxy.RequestTransformer, bool) {
layer, exists := r.getLayerAsAny(layerType, name)
if !exists {
return nil, false
}
transformer, ok := layer.(proxy.RequestTransformer)
if !ok {
return nil, false
}
return transformer, true
}
func (r *LayerRegistry) Load(layers ...Layer) {
index := make(map[store.LayerType]map[string]Layer)
for _, l := range layers {
layerType := l.LayerType()
layers, exists := index[layerType]
if !exists {
layers = make(map[string]Layer)
}
layerName := l.LayerName()
layers[layerName] = l
index[layerType] = layers
}
r.index = index
}
func NewLayerRegistry(layers ...Layer) *LayerRegistry {
registry := &LayerRegistry{
index: make(map[store.LayerType]map[string]Layer),
}
registry.Load(layers...)
return registry
}