feat: configurable default http handler
Cadoles/go-proxy/pipeline/head This commit looks good Details

This commit is contained in:
wpetit 2024-06-26 15:26:07 +02:00
parent c6b3d482cc
commit e1db6466a9
2 changed files with 16 additions and 2 deletions

View File

@ -2,6 +2,7 @@ package proxy
import (
"context"
"net/http"
"net/http/httputil"
"net/url"
)
@ -11,6 +12,7 @@ type Options struct {
RequestTransformers []RequestTransformer
ResponseTransformers []ResponseTransformer
ReverseProxyFactory ReverseProxyFactory
DefaultHandler http.Handler
}
func defaultOptions() *Options {
@ -19,6 +21,7 @@ func defaultOptions() *Options {
RequestTransformers: make([]RequestTransformer, 0),
ResponseTransformers: make([]ResponseTransformer, 0),
ReverseProxyFactory: DefaultReverseProxyFactory,
DefaultHandler: DefaultHandler,
}
}
@ -53,3 +56,13 @@ func WithReverseProxyFactory(fn ReverseProxyFactory) OptionFunc {
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)
})

View File

@ -17,6 +17,7 @@ type Proxy struct {
responseTransformers []ResponseTransformer
requestTransformers []RequestTransformer
reverseProxyFactory ReverseProxyFactory
defaultHandler http.Handler
}
// ServeHTTP implements http.Handler
@ -82,8 +83,7 @@ func (p *Proxy) proxyRequest(w http.ResponseWriter, r *http.Request) {
}
if reverser == nil {
http.Error(w, http.StatusText(http.StatusBadGateway), http.StatusBadGateway)
p.defaultHandler.ServeHTTP(w, r)
return
}
@ -103,6 +103,7 @@ func New(funcs ...OptionFunc) *Proxy {
proxy.requestTransformers = opts.RequestTransformers
proxy.responseTransformers = opts.ResponseTransformers
proxy.reverseProxyFactory = opts.ReverseProxyFactory
proxy.defaultHandler = opts.DefaultHandler
return proxy
}