go-proxy/options.go
William Petit e1db6466a9
All checks were successful
Cadoles/go-proxy/pipeline/head This commit looks good
feat: configurable default http handler
2024-06-26 15:26:07 +02:00

69 lines
1.7 KiB
Go

package proxy
import (
"context"
"net/http"
"net/http/httputil"
"net/url"
)
type Options struct {
Middlewares []Middleware
RequestTransformers []RequestTransformer
ResponseTransformers []ResponseTransformer
ReverseProxyFactory ReverseProxyFactory
DefaultHandler http.Handler
}
func defaultOptions() *Options {
return &Options{
Middlewares: make([]Middleware, 0),
RequestTransformers: make([]RequestTransformer, 0),
ResponseTransformers: make([]ResponseTransformer, 0),
ReverseProxyFactory: DefaultReverseProxyFactory,
DefaultHandler: DefaultHandler,
}
}
type OptionFunc func(*Options)
func WithMiddlewares(middlewares ...Middleware) OptionFunc {
return func(o *Options) {
o.Middlewares = middlewares
}
}
func WithRequestTransformers(transformers ...RequestTransformer) OptionFunc {
return func(o *Options) {
o.RequestTransformers = transformers
}
}
func WithResponseTransformers(transformers ...ResponseTransformer) OptionFunc {
return func(o *Options) {
o.ResponseTransformers = transformers
}
}
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)
})