From b7a3b826c5c6fc0c42a3dd29fd20348395dd4317 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Matczuk?= Date: Wed, 9 Nov 2022 10:47:17 +0100 Subject: [PATCH] proxy: add HTTPErrorHandler that allows for custom handling error handling The idea is taken from the Stripe fork [1] but instead of context it's set globally for proxy. It gives much flexibility to error handling. [1] https://github.com/stripe/goproxy/blob/3f1dfba6d1a4747c78fee7069e2f28fd6b703917/ctx.go#L21 --- https.go | 5 +++++ proxy.go | 2 ++ 2 files changed, 7 insertions(+) diff --git a/https.go b/https.go index 5a601a80..ecfaaeee 100644 --- a/https.go +++ b/https.go @@ -324,6 +324,11 @@ func (proxy *ProxyHttpServer) handleHttps(w http.ResponseWriter, r *http.Request } func httpError(w io.WriteCloser, ctx *ProxyCtx, err error) { + if ctx.Proxy.HTTPErrorHandler != nil { + ctx.Proxy.HTTPErrorHandler(w, ctx, err) + return + } + if _, err := io.WriteString(w, "HTTP/1.1 502 Bad Gateway\r\n\r\n"); err != nil { ctx.Warnf("Error responding to client: %s", err) } diff --git a/proxy.go b/proxy.go index fe096ca3..7a41d8d7 100644 --- a/proxy.go +++ b/proxy.go @@ -25,6 +25,8 @@ type ProxyHttpServer struct { respHandlers []RespHandler httpsHandlers []HttpsHandler Tr *http.Transport + // Will be invoked to return a custom response to clients when goproxy fails to connect to a proxy target + HTTPErrorHandler func(io.WriteCloser, *ProxyCtx, error) // ConnectDial will be used to create TCP connections for CONNECT requests // if nil Tr.Dial will be used ConnectDial func(network string, addr string) (net.Conn, error)