-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathclient.go
65 lines (54 loc) · 1.62 KB
/
client.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
package envoy
import (
"encoding/json"
"errors"
"fmt"
"net/http"
)
var (
// ErrNotOK is returned if any of the Envoy APIs does not return a 200
ErrNotOK = errors.New("server did not return 200")
)
// Client provides the API for interacting with the Envoy APIs
type Client struct {
address string
client *http.Client
}
// NewClient creates a new Client that will talk to an Envoy unit at *address*, creating its own http.Client underneath.
func NewClient(address string) *Client {
client := &http.Client{}
return &Client{
address: address,
client: client,
}
}
// NewClientWithHTTP creates a new Client that will talk to an Envoy unit at *address* using the provided http.Client.
func NewClientWithHTTP(address string, client *http.Client) *Client {
return &Client{
address: address,
client: client,
}
}
func (c *Client) get(url string, response interface{}) error {
resp, err := c.client.Get(fmt.Sprintf("http://%s%s", c.address, url))
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return ErrNotOK
}
return json.NewDecoder(resp.Body).Decode(response)
}
// Inventory returns the list of parts installed in the system and registered with the Envoy unit
func (c *Client) Inventory() ([]Inventory, error) {
var inventory []Inventory
err := c.get("/inventory.json?deleted=1", &inventory)
return inventory, err
}
// Production returns the current data for Production and Consumption sensors, if equipped.
func (c *Client) Production() (Production, error) {
var production Production
err := c.get("/production.json?details=1", &production)
return production, err
}