bouncer/internal/proxy/director/layer/rewriter/layer.go
William Petit 05b547da48
All checks were successful
Cadoles/bouncer/pipeline/head This commit looks good
Cadoles/bouncer/pipeline/pr-develop This commit looks good
feat: rewriter layer
2024-06-25 16:50:29 +02:00

85 lines
2.0 KiB
Go

package rewriter
import (
"net/http"
proxy "forge.cadoles.com/Cadoles/go-proxy"
"forge.cadoles.com/Cadoles/go-proxy/wildcard"
"forge.cadoles.com/cadoles/bouncer/internal/proxy/director"
"forge.cadoles.com/cadoles/bouncer/internal/store"
"github.com/pkg/errors"
"gitlab.com/wpetit/goweb/logger"
)
const LayerType store.LayerType = "rewriter"
type Layer struct{}
func (l *Layer) LayerType() store.LayerType {
return LayerType
}
func (l *Layer) Middleware(layer *store.Layer) proxy.Middleware {
return func(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
options, err := fromStoreOptions(layer.Options)
if err != nil {
logger.Error(ctx, "could not parse layer options", logger.E(errors.WithStack(err)))
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
matches := wildcard.MatchAny(r.URL.String(), options.MatchURLs...)
if !matches {
next.ServeHTTP(w, r)
return
}
if err := l.applyRequestRules(r, options); err != nil {
logger.Error(ctx, "could not apply request rules", logger.E(errors.WithStack(err)))
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
next.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
}
// ResponseTransformer implements director.ResponseTransformerLayer.
func (l *Layer) ResponseTransformer(layer *store.Layer) proxy.ResponseTransformer {
return func(r *http.Response) error {
options, err := fromStoreOptions(layer.Options)
if err != nil {
return errors.WithStack(err)
}
matches := wildcard.MatchAny(r.Request.URL.String(), options.MatchURLs...)
if !matches {
return nil
}
if err := l.applyResponseRules(r, options); err != nil {
return errors.WithStack(err)
}
return nil
}
}
func New() *Layer {
return &Layer{}
}
var (
_ director.MiddlewareLayer = &Layer{}
_ director.ResponseTransformerLayer = &Layer{}
)