diff --git a/modules/caddyhttp/reverseproxy/selectionpolicies.go b/modules/caddyhttp/reverseproxy/selectionpolicies.go index 8ab6553f4..ff4c9953f 100644 --- a/modules/caddyhttp/reverseproxy/selectionpolicies.go +++ b/modules/caddyhttp/reverseproxy/selectionpolicies.go @@ -167,7 +167,7 @@ func (r *WeightedRoundRobinSelection) Select(pool UpstreamPool, _ *http.Request, upstreams := make([]*Upstream, 0, len(weights)) for i, upstream := range pool { - if !upstream.Available() || r.Weights[i] == 0 { + if i >= len(r.Weights) || !upstream.Available() || r.Weights[i] == 0 { continue } upstreams = append(upstreams, upstream) diff --git a/modules/caddyhttp/reverseproxy/selectionpolicies_test.go b/modules/caddyhttp/reverseproxy/selectionpolicies_test.go index b8a586332..b40674ae6 100644 --- a/modules/caddyhttp/reverseproxy/selectionpolicies_test.go +++ b/modules/caddyhttp/reverseproxy/selectionpolicies_test.go @@ -131,6 +131,23 @@ func TestWeightedRoundRobinPolicy(t *testing.T) { } } +func TestWeightedRoundRobinPolicyFewerWeightsThanUpstreams(t *testing.T) { + pool := testPool() + wrrPolicy := WeightedRoundRobinSelection{ + Weights: []int{1, 1}, + totalWeight: 2, + } + req, _ := http.NewRequest("GET", "/", nil) + + pool[0].setHealthy(false) + for i := 0; i < 4; i++ { + h := wrrPolicy.Select(pool, req, nil) + if h != pool[1] { + t.Fatalf("Selection %d: got %v, want the only available weighted host %v", i+1, h, pool[1]) + } + } +} + func TestWeightedRoundRobinSelection_Validate(t *testing.T) { tests := []struct { name string