feat: configurable default http handler
All checks were successful
Cadoles/go-proxy/pipeline/head This commit looks good
All checks were successful
Cadoles/go-proxy/pipeline/head This commit looks good
This commit is contained in:
parent
c6b3d482cc
commit
e1db6466a9
13
options.go
13
options.go
@ -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)
|
||||
})
|
||||
|
5
proxy.go
5
proxy.go
@ -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
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user