-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttp.go
83 lines (70 loc) · 1.72 KB
/
http.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
package tado
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
)
const defaultBaseURL = "https://my.tado.com/api"
type input interface {
method() string
path() string
body() interface{}
}
func (c *Client) do(in input, out interface{}) error {
// ensure accesstoken is still valid
err := c.validateAccessToken()
if err != nil {
return err
}
// encode input as JSON if needed
var body io.Reader
switch in.method() {
case http.MethodPost, http.MethodPut:
buf := new(bytes.Buffer)
err := json.NewEncoder(buf).Encode(in.body())
if err != nil {
return fmt.Errorf("error encoding input: %s", err)
}
body = buf
}
// create HTTP request
req, err := http.NewRequest(in.method(), c.baseURL+in.path(), body)
if err != nil {
return err
}
// set authentication header
req.Header.Set("Authorization", "Bearer "+c.tr.AccessToken)
// set content type if needed
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
// execute HTTP request
resp, err := c.HTTPClient.Do(req)
if err != nil {
return fmt.Errorf("HTTP error: %s", err)
}
defer func() { _ = resp.Body.Close() }()
// check HTTP status
if resp.StatusCode >= http.StatusBadRequest {
// not OK, read body
body, err := ioutil.ReadAll(io.LimitReader(resp.Body, 1<<14))
if err != nil {
return fmt.Errorf("HTTP error: %s", err)
}
// return the body as error
return fmt.Errorf("error: HTTP status %d: %s", resp.StatusCode, string(body))
}
// for NoContent we do not decode any JSON
if resp.StatusCode == http.StatusNoContent {
return nil
}
// OK response, decode into output
err = json.NewDecoder(resp.Body).Decode(out)
if err != nil {
return fmt.Errorf("error decoding output: %s", err)
}
return nil
}