2017-06-03 02:55:59 +02:00
|
|
|
package middleware
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"net/http"
|
|
|
|
"net/http/httptest"
|
|
|
|
"testing"
|
|
|
|
|
2017-06-04 02:37:35 +02:00
|
|
|
"net/url"
|
|
|
|
|
2017-06-03 02:55:59 +02:00
|
|
|
"github.com/labstack/echo"
|
|
|
|
"github.com/stretchr/testify/assert"
|
|
|
|
)
|
|
|
|
|
|
|
|
type (
|
|
|
|
closeNotifyRecorder struct {
|
|
|
|
*httptest.ResponseRecorder
|
|
|
|
closed chan bool
|
|
|
|
}
|
|
|
|
)
|
|
|
|
|
|
|
|
func newCloseNotifyRecorder() *closeNotifyRecorder {
|
|
|
|
return &closeNotifyRecorder{
|
|
|
|
httptest.NewRecorder(),
|
|
|
|
make(chan bool, 1),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *closeNotifyRecorder) close() {
|
|
|
|
c.closed <- true
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *closeNotifyRecorder) CloseNotify() <-chan bool {
|
|
|
|
return c.closed
|
|
|
|
}
|
|
|
|
|
|
|
|
func TestProxy(t *testing.T) {
|
|
|
|
// Setup
|
|
|
|
t1 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
fmt.Fprint(w, "target 1")
|
|
|
|
}))
|
|
|
|
defer t1.Close()
|
2017-06-04 02:37:35 +02:00
|
|
|
url1, _ := url.Parse(t1.URL)
|
2017-06-03 02:55:59 +02:00
|
|
|
t2 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
fmt.Fprint(w, "target 2")
|
|
|
|
}))
|
|
|
|
defer t2.Close()
|
2017-06-04 02:37:35 +02:00
|
|
|
url2, _ := url.Parse(t2.URL)
|
|
|
|
|
|
|
|
targets := []*ProxyTarget{
|
|
|
|
&ProxyTarget{
|
|
|
|
URL: url1,
|
|
|
|
},
|
|
|
|
&ProxyTarget{
|
|
|
|
URL: url2,
|
|
|
|
},
|
|
|
|
}
|
2017-06-03 02:55:59 +02:00
|
|
|
config := ProxyConfig{
|
2017-06-04 02:37:35 +02:00
|
|
|
Balancer: &RandomBalancer{
|
|
|
|
Targets: targets,
|
2017-06-03 02:55:59 +02:00
|
|
|
},
|
|
|
|
}
|
|
|
|
|
|
|
|
// Random
|
|
|
|
e := echo.New()
|
|
|
|
e.Use(Proxy(config))
|
|
|
|
req := httptest.NewRequest(echo.GET, "/", nil)
|
|
|
|
rec := newCloseNotifyRecorder()
|
|
|
|
e.ServeHTTP(rec, req)
|
|
|
|
body := rec.Body.String()
|
2017-06-04 02:37:35 +02:00
|
|
|
expected := map[string]bool{
|
2017-06-03 02:55:59 +02:00
|
|
|
"target 1": true,
|
|
|
|
"target 2": true,
|
|
|
|
}
|
|
|
|
assert.Condition(t, func() bool {
|
2017-06-04 02:37:35 +02:00
|
|
|
return expected[body]
|
2017-06-03 02:55:59 +02:00
|
|
|
})
|
|
|
|
|
|
|
|
// Round-robin
|
2017-06-04 02:37:35 +02:00
|
|
|
config.Balancer = &RoundRobinBalancer{
|
|
|
|
Targets: targets,
|
|
|
|
}
|
2017-06-03 02:55:59 +02:00
|
|
|
e = echo.New()
|
|
|
|
e.Use(Proxy(config))
|
|
|
|
rec = newCloseNotifyRecorder()
|
|
|
|
e.ServeHTTP(rec, req)
|
|
|
|
body = rec.Body.String()
|
|
|
|
assert.Equal(t, "target 1", body)
|
|
|
|
rec = newCloseNotifyRecorder()
|
|
|
|
e.ServeHTTP(rec, req)
|
|
|
|
body = rec.Body.String()
|
|
|
|
assert.Equal(t, "target 2", body)
|
|
|
|
}
|