mirror of https://github.com/docker/docs.git
add basic discovery client
This commit is contained in:
parent
855598f2ac
commit
a0841874c5
|
@ -0,0 +1,40 @@
|
|||
package discovery
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const DISCOVERY_URL = "https://discovery-stage.hub.docker.com/v1"
|
||||
|
||||
// FetchSlaves returns the slaves for the discovery service at the specified endpoint
|
||||
func FetchSlaves(token string) ([]string, error) {
|
||||
resp, err := http.Get(fmt.Sprintf("%s/%s/%s", DISCOVERY_URL, "clusters", token))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
|
||||
var addrs []string
|
||||
if resp.StatusCode == http.StatusOK {
|
||||
if err := json.NewDecoder(resp.Body).Decode(&addrs); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return addrs, nil
|
||||
}
|
||||
|
||||
// RegisterSlave adds a new slave identified by the slaveID into the discovery service
|
||||
// the default TTL is 30 secs
|
||||
func RegisterSlave(addr, token string) error {
|
||||
buf := strings.NewReader(addr)
|
||||
|
||||
_, err := http.Post(fmt.Sprintf("%s/%s/%s", DISCOVERY_URL, "clusters", token), "application/json", buf)
|
||||
return err
|
||||
}
|
|
@ -0,0 +1,27 @@
|
|||
package discovery
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestRegisterLocal(t *testing.T) {
|
||||
expected := "127.0.0.1:2675"
|
||||
if err := RegisterSlave(expected, "TEST_TOKEN"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
addrs, err := FetchSlaves("TEST_TOKEN")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if len(addrs) != 1 {
|
||||
t.Fatalf("expected addr len == 1, got len = %d", len(addrs))
|
||||
}
|
||||
|
||||
if addrs[0] != expected {
|
||||
t.Fatalf("expected addr %q but received %q", expected, addrs[0])
|
||||
}
|
||||
|
||||
if err = RegisterSlave(expected, "TEST_TOKEN"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue