2023-04-24 19:53:37 +02:00
|
|
|
package proxy
|
|
|
|
|
2023-07-01 21:41:11 +02:00
|
|
|
import (
|
|
|
|
"context"
|
2024-06-26 15:26:07 +02:00
|
|
|
"net/http"
|
2023-07-01 21:41:11 +02:00
|
|
|
"net/http/httputil"
|
|
|
|
"net/url"
|
|
|
|
)
|
|
|
|
|
2023-04-24 19:53:37 +02:00
|
|
|
type Options struct {
|
2023-04-24 20:14:31 +02:00
|
|
|
Middlewares []Middleware
|
|
|
|
RequestTransformers []RequestTransformer
|
|
|
|
ResponseTransformers []ResponseTransformer
|
2023-07-01 21:41:11 +02:00
|
|
|
ReverseProxyFactory ReverseProxyFactory
|
2024-06-26 15:26:07 +02:00
|
|
|
DefaultHandler http.Handler
|
2023-04-24 19:53:37 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func defaultOptions() *Options {
|
|
|
|
return &Options{
|
2023-04-24 20:14:31 +02:00
|
|
|
Middlewares: make([]Middleware, 0),
|
|
|
|
RequestTransformers: make([]RequestTransformer, 0),
|
|
|
|
ResponseTransformers: make([]ResponseTransformer, 0),
|
2023-07-01 21:41:11 +02:00
|
|
|
ReverseProxyFactory: DefaultReverseProxyFactory,
|
2024-06-26 15:26:07 +02:00
|
|
|
DefaultHandler: DefaultHandler,
|
2023-04-24 19:53:37 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
type OptionFunc func(*Options)
|
|
|
|
|
2023-04-24 20:14:31 +02:00
|
|
|
func WithMiddlewares(middlewares ...Middleware) OptionFunc {
|
2023-04-24 19:53:37 +02:00
|
|
|
return func(o *Options) {
|
2023-04-24 20:14:31 +02:00
|
|
|
o.Middlewares = middlewares
|
2023-04-24 19:53:37 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-04-24 20:14:31 +02:00
|
|
|
func WithRequestTransformers(transformers ...RequestTransformer) OptionFunc {
|
2023-04-24 19:53:37 +02:00
|
|
|
return func(o *Options) {
|
2023-04-24 20:14:31 +02:00
|
|
|
o.RequestTransformers = transformers
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func WithResponseTransformers(transformers ...ResponseTransformer) OptionFunc {
|
|
|
|
return func(o *Options) {
|
|
|
|
o.ResponseTransformers = transformers
|
2023-04-24 19:53:37 +02:00
|
|
|
}
|
|
|
|
}
|
2023-07-01 21:41:11 +02:00
|
|
|
|
|
|
|
type ReverseProxyFactory func(ctx context.Context, target *url.URL) *httputil.ReverseProxy
|
|
|
|
|
|
|
|
func WithReverseProxyFactory(fn ReverseProxyFactory) OptionFunc {
|
|
|
|
return func(o *Options) {
|
|
|
|
o.ReverseProxyFactory = fn
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func DefaultReverseProxyFactory(ctx context.Context, target *url.URL) *httputil.ReverseProxy {
|
|
|
|
return httputil.NewSingleHostReverseProxy(target)
|
|
|
|
}
|
2024-06-26 15:26:07 +02:00
|
|
|
|
|
|
|
func WithDefaultHandler(handler http.Handler) OptionFunc {
|
|
|
|
return func(o *Options) {
|
|
|
|
o.DefaultHandler = handler
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
var DefaultHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
http.Error(w, http.StatusText(http.StatusBadGateway), http.StatusBadGateway)
|
|
|
|
})
|