go-proxy/proxy.go

122 lines
2.4 KiB
Go
Raw Normal View History

2023-04-24 19:53:37 +02:00
package proxy
import (
"fmt"
"net/http"
"net/http/httputil"
"net/url"
"sync"
"forge.cadoles.com/Cadoles/go-proxy/util"
"github.com/pkg/errors"
)
type Proxy struct {
2023-04-24 20:14:31 +02:00
reversers sync.Map
handler http.Handler
responseTransformers []ResponseTransformer
requestTransformers []RequestTransformer
reverseProxyFactory ReverseProxyFactory
defaultHandler http.Handler
2023-04-24 19:53:37 +02:00
}
// ServeHTTP implements http.Handler
func (p *Proxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
p.handler.ServeHTTP(w, r)
}
func (p *Proxy) proxyRequest(w http.ResponseWriter, r *http.Request) {
var reverser *httputil.ReverseProxy
key := fmt.Sprintf("%s://%s", r.URL.Scheme, r.URL.Host)
ctx := r.Context()
2023-04-24 19:53:37 +02:00
createAndStore := func() {
target := &url.URL{
Scheme: r.URL.Scheme,
Host: r.URL.Host,
}
2023-04-24 20:14:31 +02:00
if target.Host == "" || target.Scheme == "" {
return
}
reverser = p.reverseProxyFactory(ctx, target)
if reverser == nil {
return
}
2023-04-24 19:53:37 +02:00
originalDirector := reverser.Director
2023-04-24 20:14:31 +02:00
if len(p.requestTransformers) > 0 {
2023-04-24 19:53:37 +02:00
reverser.Director = func(r *http.Request) {
originalDirector(r)
2023-04-24 20:14:31 +02:00
for _, t := range p.requestTransformers {
t(r)
}
2023-04-24 19:53:37 +02:00
}
}
2023-04-24 20:14:31 +02:00
if len(p.responseTransformers) > 0 {
2023-04-24 19:53:37 +02:00
reverser.ModifyResponse = func(r *http.Response) error {
2023-04-24 20:14:31 +02:00
for _, t := range p.responseTransformers {
if err := t(r); err != nil {
return errors.WithStack(err)
}
2023-04-24 19:53:37 +02:00
}
return nil
}
}
p.reversers.Store(key, reverser)
}
raw, exists := p.reversers.Load(key)
if !exists {
createAndStore()
}
reverser, ok := raw.(*httputil.ReverseProxy)
if !ok {
createAndStore()
}
2023-04-24 20:14:31 +02:00
if reverser == nil {
p.defaultHandler.ServeHTTP(w, r)
2023-04-24 20:14:31 +02:00
return
}
2023-04-24 19:53:37 +02:00
reverser.ServeHTTP(w, r)
}
func New(funcs ...OptionFunc) *Proxy {
opts := defaultOptions()
for _, fn := range funcs {
fn(opts)
}
proxy := &Proxy{}
handler := http.HandlerFunc(proxy.proxyRequest)
proxy.handler = createMiddlewareChain(handler, opts.Middlewares)
2023-04-24 20:14:31 +02:00
proxy.requestTransformers = opts.RequestTransformers
proxy.responseTransformers = opts.ResponseTransformers
proxy.reverseProxyFactory = opts.ReverseProxyFactory
proxy.defaultHandler = opts.DefaultHandler
2023-04-24 19:53:37 +02:00
return proxy
}
var _ http.Handler = &Proxy{}
func createMiddlewareChain(handler http.Handler, middlewares []Middleware) http.Handler {
util.Reverse(middlewares)
for _, m := range middlewares {
handler = m(handler)
}
return handler
}