Skip to content

Commit 179e74f

Browse files
committed
Add test covering proxy retries on timeout
1 parent dbbaadd commit 179e74f

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed

middleware/proxy.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -239,6 +239,7 @@ func (b *roundRobinBalancer) Next(c echo.Context) *ProxyTarget {
239239
} else if len(b.targets) == 1 {
240240
return b.targets[0]
241241
}
242+
242243
// reset the index if out of bounds
243244
if b.i >= len(b.targets) {
244245
b.i = 0

middleware/proxy_test.go

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -573,6 +573,62 @@ func TestProxyRetries(t *testing.T) {
573573
}
574574
}
575575

576+
func TestProxyRetryWithBackendTimeout(t *testing.T) {
577+
578+
transport := http.DefaultTransport.(*http.Transport).Clone()
579+
transport.ResponseHeaderTimeout = time.Millisecond * 500
580+
581+
timeoutBackend := httptest.NewServer(
582+
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
583+
time.Sleep(1 * time.Second)
584+
w.WriteHeader(404)
585+
}),
586+
)
587+
defer timeoutBackend.Close()
588+
589+
timeoutTargetURL, _ := url.Parse(timeoutBackend.URL)
590+
goodBackend := httptest.NewServer(
591+
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
592+
w.WriteHeader(200)
593+
}),
594+
)
595+
defer goodBackend.Close()
596+
597+
goodTargetURL, _ := url.Parse(goodBackend.URL)
598+
e := echo.New()
599+
e.Use(ProxyWithConfig(
600+
ProxyConfig{
601+
Transport: transport,
602+
Balancer: NewRoundRobinBalancer([]*ProxyTarget{
603+
{
604+
Name: "Timeout",
605+
URL: timeoutTargetURL,
606+
},
607+
{
608+
Name: "Good",
609+
URL: goodTargetURL,
610+
},
611+
}),
612+
RetryCount: 1,
613+
},
614+
))
615+
616+
var wg sync.WaitGroup
617+
for i := 0; i < 20; i++ {
618+
wg.Add(1)
619+
go func() {
620+
defer wg.Done()
621+
req := httptest.NewRequest(http.MethodGet, "/", nil)
622+
rec := httptest.NewRecorder()
623+
e.ServeHTTP(rec, req)
624+
assert.Contains(t, []int{200, 502}, rec.Code)
625+
}()
626+
}
627+
628+
wg.Wait()
629+
630+
}
631+
576632
func TestProxyErrorHandler(t *testing.T) {
577633

578634
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

0 commit comments

Comments
 (0)