-
Notifications
You must be signed in to change notification settings - Fork 27
/
client.go
94 lines (75 loc) · 2.01 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package command
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"time"
"github.com/hashicorp/errwrap"
"github.com/timeglass/glass/model"
)
var ErrDaemonDown = errors.New("Daemon doesn't appears to be running.")
type Client struct {
info *model.Daemon
*http.Client
}
type StatusData struct {
Time string
MostRecentVersion string
CurrentVersion string
}
func NewClient(info *model.Daemon) *Client {
return &Client{
info: info,
Client: &http.Client{
Timeout: time.Duration(400 * time.Millisecond),
},
}
}
func (c *Client) Call(method string) error {
resp, err := c.Get(fmt.Sprintf("http://%s/%s", c.info.Addr, method))
if err != nil {
return ErrDaemonDown
} else if resp.StatusCode != 200 {
return fmt.Errorf("Unexpected StatusCode from Daemon: %d", resp.StatusCode)
}
return nil
}
func (c *Client) Lap() (time.Duration, error) {
resp, err := c.Get(fmt.Sprintf("http://%s/timer.lap", c.info.Addr))
if err != nil {
return 0, ErrDaemonDown
} else if resp.StatusCode != 200 {
return 0, fmt.Errorf("Unexpected StatusCode from Daemon: %d", resp.StatusCode)
}
dec := json.NewDecoder(resp.Body)
defer resp.Body.Close()
status := struct {
Time string
}{}
err = dec.Decode(&status)
if err != nil {
return 0, errwrap.Wrapf("Failed to decode json response: {{err}}", err)
}
d, err := time.ParseDuration(status.Time)
if err != nil {
return 0, errwrap.Wrapf(fmt.Sprintf("Failed to parse '%s' as a time duration: {{err}}", status.Time), err)
}
return d, nil
}
func (c *Client) GetStatus() (*StatusData, error) {
resp, err := c.Get(fmt.Sprintf("http://%s/timer.status", c.info.Addr))
if err != nil {
return nil, ErrDaemonDown
} else if resp.StatusCode != 200 {
return nil, fmt.Errorf("Unexpected StatusCode from Daemon: %d", resp.StatusCode)
}
dec := json.NewDecoder(resp.Body)
defer resp.Body.Close()
status := &StatusData{}
err = dec.Decode(&status)
if err != nil {
return status, errwrap.Wrapf("Failed to decode json response: {{err}}", err)
}
return status, nil
}