proxy: Add the first policy (#1513)

* Add the first policy which sends the request to the first available host

* Make the error message clear. As we expect the second not first upstream
host.
This commit is contained in:
Peer Beckmann 2017-03-14 16:57:08 +01:00 committed by Matt Holt
parent 36a62f0915
commit a148b92381
2 changed files with 31 additions and 0 deletions

View File

@ -22,6 +22,7 @@ func init() {
RegisterPolicy("least_conn", func() Policy { return &LeastConn{} }) RegisterPolicy("least_conn", func() Policy { return &LeastConn{} })
RegisterPolicy("round_robin", func() Policy { return &RoundRobin{} }) RegisterPolicy("round_robin", func() Policy { return &RoundRobin{} })
RegisterPolicy("ip_hash", func() Policy { return &IPHash{} }) RegisterPolicy("ip_hash", func() Policy { return &IPHash{} })
RegisterPolicy("first", func() Policy { return &First{} })
} }
// Random is a policy that selects up hosts from a pool at random. // Random is a policy that selects up hosts from a pool at random.
@ -131,3 +132,16 @@ func (r *IPHash) Select(pool HostPool, request *http.Request) *UpstreamHost {
} }
return nil return nil
} }
// First is a policy that selects the fist available host
type First struct{}
// Select selects the first host from the pool, that is available
func (r *First) Select(pool HostPool, request *http.Request) *UpstreamHost {
for _, host := range pool {
if host.Available() {
return host
}
}
return nil
}

View File

@ -226,3 +226,20 @@ func TestIPHashPolicy(t *testing.T) {
t.Error("Expected ip hash policy host to be nil.") t.Error("Expected ip hash policy host to be nil.")
} }
} }
func TestFirstPolicy(t *testing.T) {
pool := testPool()
firstPolicy := &First{}
req := httptest.NewRequest(http.MethodGet, "/", nil)
h := firstPolicy.Select(pool, req)
if h != pool[0] {
t.Error("Expected first policy host to be the first host.")
}
pool[0].Unhealthy = 1
h = firstPolicy.Select(pool, req)
if h != pool[1] {
t.Error("Expected first policy host to be the second host.")
}
}