-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
79 lines (71 loc) · 1.41 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
package twentynine
import (
"bytes"
"encoding/json"
"io"
"io/ioutil"
"net/http"
"time"
)
type Client struct {
url string
http http.Client
}
type ClientOption func(cli *Client)
func OptTimeout(timeout time.Duration) ClientOption {
return func(cli *Client) { cli.http.Timeout = timeout }
}
func OptURL(rawurl string) ClientOption {
return func(cli *Client) { cli.url = rawurl }
}
func NewClient(opts ...ClientOption) *Client {
c := &Client{
url: TwentyNineApiUrl,
}
for _, opt := range opts {
opt(c)
}
return c
}
func (cli *Client) Links() (links []Link, err error) {
r, err := cli.http.Get(cli.url)
if err != nil {
return
}
if r.StatusCode != http.StatusOK {
msgBuf, _ := ioutil.ReadAll(r.Body)
err = Error{
Code: r.StatusCode,
Message: string(msgBuf),
}
return
}
if err = json.NewDecoder(r.Body).Decode(&links); err != io.EOF {
return
}
err = nil // err ?= io.EOF
return
}
func (cli *Client) LinkLink(link Link) (err error) {
buf := new(bytes.Buffer)
if err = json.NewEncoder(buf).Encode(link); err != nil {
return
}
r, err := cli.http.Post(cli.url, "application/json", buf)
if err != nil {
return
}
if r.StatusCode != http.StatusOK {
msgBuf, _ := ioutil.ReadAll(r.Body)
err = Error{
Code: r.StatusCode,
Message: string(msgBuf),
}
return
}
if err = json.NewDecoder(r.Body).Decode(&link); err != io.EOF {
return
}
err = nil // err ?= io.EOF
return
}