etcdhttp: add Peers.Endpoints

release-2.0
Brian Waldon 2014-09-10 15:22:50 -07:00
parent 2b39ee1bb3
commit bafe960dba
2 changed files with 70 additions and 8 deletions

View File

@ -85,6 +85,20 @@ func (ps Peers) IDs() []int64 {
return ids
}
// Endpoints returns a list of all peer addresses. Each address is
// prefixed with "http://". The returned list is sorted (asc).
func (ps Peers) Endpoints() []string {
endpoints := make([]string, 0)
for _, addrs := range ps {
for _, addr := range addrs {
endpoints = append(endpoints, addScheme(addr))
}
}
sort.Strings(endpoints)
return endpoints
}
var errClosed = errors.New("etcdhttp: client closed connection")
const DefaultTimeout = 500 * time.Millisecond
@ -209,14 +223,8 @@ func (h Handler) serveMachines(w http.ResponseWriter, r *http.Request) {
allow(w, "GET", "HEAD")
return
}
urls := make([]string, 0)
for _, addrs := range h.Peers {
for _, addr := range addrs {
urls = append(urls, addScheme(addr))
}
}
sort.Strings(urls)
w.Write([]byte(strings.Join(urls, ", ")))
endpoints := h.Peers.Endpoints()
w.Write([]byte(strings.Join(endpoints, ", ")))
}
func (h Handler) serveRaft(ctx context.Context, w http.ResponseWriter, r *http.Request) {

View File

@ -397,3 +397,57 @@ func TestServeMachines(t *testing.T) {
t.Errorf("header = %d, want %d", writer.Code, http.StatusOK)
}
}
func TestPeersEndpoints(t *testing.T) {
tests := []struct {
peers Peers
endpoints []string
}{
// single peer with a single address
{
peers: Peers(map[int64][]string{
1: []string{"192.0.2.1"},
}),
endpoints: []string{"http://192.0.2.1"},
},
// single peer with a single address with a port
{
peers: Peers(map[int64][]string{
1: []string{"192.0.2.1:8001"},
}),
endpoints: []string{"http://192.0.2.1:8001"},
},
// several peers explicitly unsorted
{
peers: Peers(map[int64][]string{
2: []string{"192.0.2.3", "192.0.2.4"},
3: []string{"192.0.2.5", "192.0.2.6"},
1: []string{"192.0.2.1", "192.0.2.2"},
}),
endpoints: []string{"http://192.0.2.1", "http://192.0.2.2", "http://192.0.2.3", "http://192.0.2.4", "http://192.0.2.5", "http://192.0.2.6"},
},
// no peers
{
peers: Peers(map[int64][]string{}),
endpoints: []string{},
},
// peer with no endpoints
{
peers: Peers(map[int64][]string{
3: []string{},
}),
endpoints: []string{},
},
}
for i, tt := range tests {
endpoints := tt.peers.Endpoints()
if !reflect.DeepEqual(tt.endpoints, endpoints) {
t.Errorf("#%d: peers.Endpoints() incorrect: want=%#v got=%#v", i, tt.endpoints, endpoints)
}
}
}