/
api.go
75 lines (60 loc) · 1.31 KB
/
api.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
package place
import (
"encoding/json"
"errors"
"fmt"
"image/color"
"net/http"
"net/url"
"strconv"
"time"
)
const (
timeURL = "https://www.reddit.com/api/place/time.json"
drawURL = "https://www.reddit.com/api/place/draw.json"
)
type Client struct {
*http.Client
}
func (c Client) WaitTime() (time.Duration, error) {
resp, err := c.Get(timeURL)
if err != nil {
return 0, err
}
if resp.StatusCode != http.StatusOK {
return 0, errors.New(resp.Status)
}
defer resp.Body.Close()
var t Time
if err := json.NewDecoder(resp.Body).Decode(&t); err != nil {
return 0, err
}
return t.Duration(), nil
}
type Time struct {
WaitSeconds float64 `json:"wait_seconds"`
}
func (t Time) Duration() time.Duration {
d, _ := time.ParseDuration(fmt.Sprintf("%fs", t.WaitSeconds))
return d
}
func (c Client) Draw(x, y int, color color.Color) (time.Duration, error) {
cIndex := DefaultColorPalette.Index(color)
v := url.Values{}
v.Add("x", strconv.Itoa(x))
v.Add("y", strconv.Itoa(y))
v.Add("color", strconv.Itoa(cIndex))
resp, err := c.PostForm(drawURL, v)
if err != nil {
return 0, err
}
if resp.StatusCode != http.StatusOK {
return 0, errors.New(resp.Status)
}
defer resp.Body.Close()
var t Time
if err := json.NewDecoder(resp.Body).Decode(&t); err != nil {
return 0, err
}
return t.Duration(), nil
}