-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathconn.go
114 lines (92 loc) · 2.49 KB
/
conn.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
package tesla
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
)
const (
// DefaultBaseURL is the URL for the Tesla owner's API.
DefaultBaseURL = "https://owner-api.teslamotors.com"
)
// Conn represents a connection to the Tesla owner's API.
type Conn struct {
rt http.RoundTripper
baseURL string
clientID string
clientSecret string
accessToken string
refreshToken string
debugMode bool
}
// NewConn creates a new connection.
func NewConn(rt http.RoundTripper, baseURL, clientID, clientSecret string) *Conn {
return &Conn{
rt: rt,
baseURL: baseURL,
clientID: clientID,
clientSecret: clientSecret,
}
}
// SetDebugMode turns debug mode on or off. If on, all requests and responses are dumped in their
// raw state to stdout.
func (c *Conn) SetDebugMode(debug bool) {
if debug {
c.rt = &debugTransport{
r: c.rt,
}
} else if rt, ok := c.rt.(*debugTransport); ok {
c.rt = rt.r
}
}
// SetRefreshToken allows you to override the refresh token received from Authenticate.
func (c *Conn) SetRefreshToken(refreshToken string) {
c.refreshToken = refreshToken
}
// SetAccessToken allows you to override the access token received from Authenticate.
func (c *Conn) SetAccessToken(accessToken string) {
c.accessToken = accessToken
}
func (c *Conn) doRequest(method, url string, reqBody, respBody interface{}) error {
var reqBodyReader io.Reader
if reqBody != nil {
reqBytes, err := json.Marshal(reqBody)
if err != nil {
return fmt.Errorf("error marshaling request body: %w", err)
}
reqBodyReader = bytes.NewReader(reqBytes)
}
req, err := http.NewRequest(method, fmt.Sprintf("%s%s", c.baseURL, url), reqBodyReader)
if err != nil {
return fmt.Errorf("error creating http request: %w", err)
}
if reqBodyReader != nil {
req.Header.Add("Content-Type", "application/json")
}
if c.accessToken != "" {
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", c.accessToken))
}
resp, err := c.rt.RoundTrip(req)
if resp != nil {
defer resp.Body.Close()
}
if err != nil {
return fmt.Errorf("error performing http request: %w", err)
}
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("%w", HTTPStatusError{
statusCode: resp.StatusCode,
})
}
respBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("error reading http response body: %w", err)
}
err = json.Unmarshal(respBytes, respBody)
if err != nil {
return fmt.Errorf("error unmarshaling response: %w", err)
}
return nil
}