-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
115 lines (104 loc) · 2.4 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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package lynx
import (
"bytes"
"encoding/json"
"fmt"
mqtt "github.com/eclipse/paho.mqtt.golang"
"io"
"net/http"
"strings"
"time"
)
// Options is connection options for the client
type Options struct {
Authenticator Authentication
APIBase string
MqttOptions *mqtt.ClientOptions
HTTPClient *http.Client
}
// Client is the main client for Lynx integration
type Client struct {
opt *Options
c *http.Client
Mqtt mqtt.Client
}
// V3Client is a client implementing the V3 endpoints
type V3Client struct {
c *Client
}
// V3 Returns the V3 client
func (c *Client) V3() *V3Client {
return &V3Client{c: c}
}
// NewClient create a new client for V2 API:s with specified options
func NewClient(options *Options) *Client {
options.APIBase = strings.TrimSuffix(options.APIBase, "/")
var mq mqtt.Client
if options.MqttOptions != nil {
options.Authenticator.SetMQTTAuth(options.MqttOptions)
mq = mqtt.NewClient(options.MqttOptions)
}
if options.HTTPClient == nil {
options.HTTPClient = &http.Client{
Timeout: time.Second * 5,
}
}
return &Client{
c: options.HTTPClient,
opt: options,
Mqtt: mq,
}
}
func requestError(response *http.Response) error {
if response.StatusCode != http.StatusOK {
err := Error{
Code: response.StatusCode,
}
if response.StatusCode == http.StatusRequestURITooLong {
return err
}
if response.StatusCode != http.StatusNoContent {
jsonError := json.NewDecoder(response.Body).Decode(&err)
if jsonError != nil {
return jsonError
}
}
return err
}
return nil
}
func requestBody(data interface{}) io.Reader {
bin, _ := json.Marshal(data)
body := bytes.NewReader(bin)
return body
}
func (c *Client) do(r *http.Request, out interface{}) error {
response, err := c.c.Do(r)
if err != nil {
return err
}
defer response.Body.Close()
if err := requestError(response); err != nil {
return err
}
if out != nil {
if err := json.NewDecoder(response.Body).Decode(out); err != nil {
return err
}
}
return nil
}
func (c *Client) newRequest(method, path string, body io.Reader) *http.Request {
uri := fmt.Sprintf("%s/%s", c.opt.APIBase, path)
r, _ := http.NewRequest(method, uri, body)
c.opt.Authenticator.SetHTTPAuth(r)
return r
}
// Ping verify that the api is responding
func (c *Client) Ping() error {
request := c.newRequest(http.MethodGet, "/api/v2/ping", nil)
if err := c.do(request, nil); err != nil {
return err
}
return nil
}