Skip to content

Commit 6463bcb

Browse files
authored
added ModifyResponse option to ProxyConfig (#1622)
Co-authored-by: Peter C <[email protected]>
1 parent 8dd25c3 commit 6463bcb

File tree

3 files changed

+22
-1
lines changed

3 files changed

+22
-1
lines changed

middleware/proxy.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,9 @@ type (
4545
// Examples: If custom TLS certificates are required.
4646
Transport http.RoundTripper
4747

48+
// ModifyResponse defines function to modify response from ProxyTarget.
49+
ModifyResponse func(*http.Response) error
50+
4851
rewriteRegex map[*regexp.Regexp]string
4952
}
5053

middleware/proxy_1_11.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,5 +20,6 @@ func proxyHTTP(tgt *ProxyTarget, c echo.Context, config ProxyConfig) http.Handle
2020
c.Set("_error", echo.NewHTTPError(http.StatusBadGateway, fmt.Sprintf("remote %s unreachable, could not forward: %v", desc, err)))
2121
}
2222
proxy.Transport = config.Transport
23+
proxy.ModifyResponse = config.ModifyResponse
2324
return proxy
2425
}

middleware/proxy_test.go

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
package middleware
22

33
import (
4+
"bytes"
45
"fmt"
6+
"io/ioutil"
57
"net"
68
"net/http"
79
"net/http/httptest"
@@ -104,11 +106,26 @@ func TestProxy(t *testing.T) {
104106
e.ServeHTTP(rec, req)
105107
assert.Equal(t, "/user/jack/order/1", req.URL.Path)
106108
assert.Equal(t, http.StatusOK, rec.Code)
107-
req.URL.Path = "/users/jill/orders/T%2FcO4lW%2Ft%2FVp%2F"
109+
req.URL.Path = "/users/jill/orders/T%2FcO4lW%2Ft%2FVp%2F"
108110
e.ServeHTTP(rec, req)
109111
assert.Equal(t, "/user/jill/order/T%2FcO4lW%2Ft%2FVp%2F", req.URL.Path)
110112
assert.Equal(t, http.StatusOK, rec.Code)
111113

114+
// ModifyResponse
115+
e = echo.New()
116+
e.Use(ProxyWithConfig(ProxyConfig{
117+
Balancer: rrb,
118+
ModifyResponse: func(res *http.Response) error {
119+
res.Body = ioutil.NopCloser(bytes.NewBuffer([]byte("modified")))
120+
res.Header.Set("X-Modified", "1")
121+
return nil
122+
},
123+
}))
124+
rec = httptest.NewRecorder()
125+
e.ServeHTTP(rec, req)
126+
assert.Equal(t, "modified", rec.Body.String())
127+
assert.Equal(t, "1", rec.Header().Get("X-Modified"))
128+
112129
// ProxyTarget is set in context
113130
contextObserver := func(next echo.HandlerFunc) echo.HandlerFunc {
114131
return func(c echo.Context) (err error) {

0 commit comments

Comments
 (0)