go-proxy/options.go

69 lines
1.7 KiB
Go
Raw Normal View History

2023-04-24 19:53:37 +02:00
package proxy
import (
"context"
"net/http"
"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
ReverseProxyFactory ReverseProxyFactory
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),
ReverseProxyFactory: DefaultReverseProxyFactory,
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
}
}
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)
}
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)
})