forked from etcd-io/etcd
/
get.go
83 lines (59 loc) · 1.48 KB
/
get.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package etcd
import (
"encoding/json"
"github.com/coreos/etcd/store"
"io/ioutil"
"net/http"
"path"
)
func (c *Client) Get(key string) ([]*store.Response, error) {
logger.Debugf("get %s [%s]", key, c.cluster.Leader)
resp, err := c.sendRequest("GET", path.Join("keys", key), "")
if err != nil {
return nil, err
}
b, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
return nil, handleError(b)
}
return convertGetResponse(b)
}
// GetTo gets the value of the key from a given machine address.
// If the given machine is not available it returns an error.
// Mainly use for testing purpose
func (c *Client) GetFrom(key string, addr string) ([]*store.Response, error) {
httpPath := c.createHttpPath(addr, path.Join(version, "keys", key))
resp, err := c.httpClient.Get(httpPath)
if err != nil {
return nil, err
}
b, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
return nil, handleError(b)
}
return convertGetResponse(b)
}
// Convert byte stream to response.
func convertGetResponse(b []byte) ([]*store.Response, error) {
var results []*store.Response
var result *store.Response
err := json.Unmarshal(b, &result)
if err != nil {
err = json.Unmarshal(b, &results)
if err != nil {
return nil, err
}
} else {
results = make([]*store.Response, 1)
results[0] = result
}
return results, nil
}