1
0
mirror of https://github.com/labstack/echo.git synced 2025-01-26 03:20:08 +02:00

added ModifyResponse option to ProxyConfig (#1622)

Co-authored-by: Peter C <petoc@users.noreply.github.com>
This commit is contained in:
Peter C 2020-08-28 02:51:27 +02:00 committed by GitHub
parent 8dd25c39ce
commit 6463bcb190
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 22 additions and 1 deletions

View File

@ -45,6 +45,9 @@ type (
// Examples: If custom TLS certificates are required.
Transport http.RoundTripper
// ModifyResponse defines function to modify response from ProxyTarget.
ModifyResponse func(*http.Response) error
rewriteRegex map[*regexp.Regexp]string
}

View File

@ -20,5 +20,6 @@ func proxyHTTP(tgt *ProxyTarget, c echo.Context, config ProxyConfig) http.Handle
c.Set("_error", echo.NewHTTPError(http.StatusBadGateway, fmt.Sprintf("remote %s unreachable, could not forward: %v", desc, err)))
}
proxy.Transport = config.Transport
proxy.ModifyResponse = config.ModifyResponse
return proxy
}

View File

@ -1,7 +1,9 @@
package middleware
import (
"bytes"
"fmt"
"io/ioutil"
"net"
"net/http"
"net/http/httptest"
@ -104,11 +106,26 @@ func TestProxy(t *testing.T) {
e.ServeHTTP(rec, req)
assert.Equal(t, "/user/jack/order/1", req.URL.Path)
assert.Equal(t, http.StatusOK, rec.Code)
req.URL.Path = "/users/jill/orders/T%2FcO4lW%2Ft%2FVp%2F"
req.URL.Path = "/users/jill/orders/T%2FcO4lW%2Ft%2FVp%2F"
e.ServeHTTP(rec, req)
assert.Equal(t, "/user/jill/order/T%2FcO4lW%2Ft%2FVp%2F", req.URL.Path)
assert.Equal(t, http.StatusOK, rec.Code)
// ModifyResponse
e = echo.New()
e.Use(ProxyWithConfig(ProxyConfig{
Balancer: rrb,
ModifyResponse: func(res *http.Response) error {
res.Body = ioutil.NopCloser(bytes.NewBuffer([]byte("modified")))
res.Header.Set("X-Modified", "1")
return nil
},
}))
rec = httptest.NewRecorder()
e.ServeHTTP(rec, req)
assert.Equal(t, "modified", rec.Body.String())
assert.Equal(t, "1", rec.Header().Get("X-Modified"))
// ProxyTarget is set in context
contextObserver := func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) (err error) {