1
0
mirror of https://github.com/labstack/echo.git synced 2024-12-24 20:14:31 +02:00

Proxy middleware refactor

Signed-off-by: Vishal Rana <vr@labstack.com>
This commit is contained in:
Vishal Rana 2017-06-15 08:19:18 -07:00
parent e827c85dc5
commit e1e3ebe5a1
3 changed files with 25 additions and 10 deletions

View File

@ -50,7 +50,7 @@ func BodyDump(handler BodyDumpHandler) echo.MiddlewareFunc {
} }
// BodyDumpWithConfig returns a BodyDump middleware with config. // BodyDumpWithConfig returns a BodyDump middleware with config.
// See: `BodyConfig()`. // See: `BodyDump()`.
func BodyDumpWithConfig(config BodyDumpConfig) echo.MiddlewareFunc { func BodyDumpWithConfig(config BodyDumpConfig) echo.MiddlewareFunc {
// Defaults // Defaults
if config.Handler == nil { if config.Handler == nil {

View File

@ -53,6 +53,13 @@ type (
} }
) )
var (
// DefaultProxyConfig is the default Proxy middleware config.
DefaultProxyConfig = ProxyConfig{
Skipper: DefaultSkipper,
}
)
func proxyHTTP(t *ProxyTarget) http.Handler { func proxyHTTP(t *ProxyTarget) http.Handler {
return httputil.NewSingleHostReverseProxy(t.URL) return httputil.NewSingleHostReverseProxy(t.URL)
} }
@ -113,8 +120,18 @@ func (r *RoundRobinBalancer) Next() *ProxyTarget {
return t return t
} }
// Proxy returns an HTTP/WebSocket reverse proxy middleware. // Proxy returns a Proxy middleware.
func Proxy(config ProxyConfig) echo.MiddlewareFunc { //
// Proxy middleware forwards a request to upstream server using a configured load balancing technique.
func Proxy(balancer ProxyBalancer) echo.MiddlewareFunc {
c := DefaultProxyConfig
c.Balancer = balancer
return ProxyWithConfig(c)
}
// ProxyWithConfig returns a Proxy middleware with config.
// See: `Proxy()`
func ProxyWithConfig(config ProxyConfig) echo.MiddlewareFunc {
// Defaults // Defaults
if config.Skipper == nil { if config.Skipper == nil {
config.Skipper = DefaultLoggerConfig.Skipper config.Skipper = DefaultLoggerConfig.Skipper

View File

@ -55,15 +55,13 @@ func TestProxy(t *testing.T) {
URL: url2, URL: url2,
}, },
} }
config := ProxyConfig{ rb := &RandomBalancer{
Balancer: &RandomBalancer{ Targets: targets,
Targets: targets,
},
} }
// Random // Random
e := echo.New() e := echo.New()
e.Use(Proxy(config)) e.Use(Proxy(rb))
req := httptest.NewRequest(echo.GET, "/", nil) req := httptest.NewRequest(echo.GET, "/", nil)
rec := newCloseNotifyRecorder() rec := newCloseNotifyRecorder()
e.ServeHTTP(rec, req) e.ServeHTTP(rec, req)
@ -77,11 +75,11 @@ func TestProxy(t *testing.T) {
}) })
// Round-robin // Round-robin
config.Balancer = &RoundRobinBalancer{ rrb := &RoundRobinBalancer{
Targets: targets, Targets: targets,
} }
e = echo.New() e = echo.New()
e.Use(Proxy(config)) e.Use(Proxy(rrb))
rec = newCloseNotifyRecorder() rec = newCloseNotifyRecorder()
e.ServeHTTP(rec, req) e.ServeHTTP(rec, req)
body = rec.Body.String() body = rec.Body.String()