-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathclient.go
More file actions
227 lines (177 loc) · 4.95 KB
/
client.go
File metadata and controls
227 lines (177 loc) · 4.95 KB
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
// Package gohvapi provides a simple golang interface to the HostVirtual
// Rest API at https://bapi.vr.org/
package gohvapi
import (
"bytes"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"os"
"strconv"
"strings"
)
// Version, BaseEndpoint, ContentType constants
const (
Version = "0.0.1"
BaseEndpoint = "https://bapi.vr.org/"
ContentType = "application/json"
)
// Client is the main object (struct) to which we attach most
// methods/functions.
// It has the following fields:
// (client, userAgent, endPoint, apiKey)
type Client struct {
client *http.Client
userAgent string
endPoint *url.URL
apiKey string
}
// GetKeyFromEnv is a simple function to try to yank the value for
// "VR_API_KEY" from the environment
func GetKeyFromEnv() string {
return os.Getenv("VR_API_KEY")
}
// NewClient is the main entrypoint for instantiating a Client struct.
// It takes your API Key as it's sole argument
// and returns the Client struct ready to talk to the API
func NewClient(apikey string) *Client {
useragent := "gohvapi/" + Version
transport := &http.Transport{
TLSNextProto: make(
map[string]func(string, *tls.Conn) http.RoundTripper,
),
}
client := http.DefaultClient
client.Transport = transport
endpoint, _ := url.Parse(BaseEndpoint)
return &Client{
userAgent: useragent,
client: client,
endPoint: endpoint,
apiKey: apikey,
}
}
// apiPath is just a short internal function
// for forcing the prepending of / to the url
func apiPath(path string) string {
if strings.HasPrefix(path, "/") {
return fmt.Sprintf("%s", path)
}
return fmt.Sprintf("/%s", path)
}
// apiKeyPath is just a short internal function for appending the key to the url
func apiKeyPath(path, apiKey string) string {
if strings.Contains(path, "?") {
return path + "&key=" + apiKey
}
return path + "?key=" + apiKey
}
// get internal method on Client struct for providing the HTTP GET call
func (c *Client) get(path string, data interface{}) error {
req, err := c.newRequest("GET", apiPath(path), nil)
if err != nil {
return err
}
return c.do(req, data)
}
// post internal method on Client struct for providing the HTTP POST call
func (c *Client) post(path string, values []byte, data interface{}) error {
fmt.Println(string(values))
req, err := c.newRequest("POST", apiPath(path), bytes.NewBuffer(values))
if err != nil {
return err
}
return c.do(req, data)
}
// put internal method on Client struct for providing the HTTP PUT call
func (c *Client) put(path string, values []byte, data interface{}) error {
fmt.Println(string(values))
req, err := c.newRequest("PUT", apiPath(path), bytes.NewBuffer(values))
if err != nil {
return err
}
return c.do(req, data)
}
// patch internal method on Client struct for providing the HTTP PATCH call
func (c *Client) patch(path string, values url.Values, data interface{}) error {
req, err := c.newRequest(
"PATCH", apiPath(path), strings.NewReader(values.Encode()),
)
if err != nil {
return err
}
return c.do(req, data)
}
// delete internal method on Client struct for providing the HTTP DELETE call
func (c *Client) delete(path string, values url.Values, data interface{}) error {
req, err := c.newRequest("DELETE", apiPath(path), nil)
if err != nil {
return err
}
return c.do(req, data)
}
// Two functions (newRequest, do) below are used by the http method name functions above
// newRequest internal method on Client struct to be wrapped inside the above http method
// named functions for doing the actual work of the get/post/put/patch/delete methods
func (c *Client) newRequest(method string, path string, body io.Reader) (*http.Request, error) {
relPath, err := url.Parse(apiKeyPath(path, c.apiKey))
if err != nil {
return nil, err
}
url := c.endPoint.ResolveReference(relPath)
req, err := http.NewRequest(method, url.String(), body)
if err != nil {
return nil, err
}
req.Header.Add("User-Agent", c.userAgent)
req.Header.Add("Accept", ContentType)
return req, nil
}
//do internal method on Client struct for making the HTTP calls
func (c *Client) do(req *http.Request, data interface{}) error {
var apiError error
resp, err := c.client.Do(req)
if err != nil {
return err
}
body, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
return err
}
if resp.StatusCode == http.StatusOK {
//fmt.Println(string(body))
if data != nil {
if err := json.Unmarshal(body, data); err != nil {
return err
}
}
return nil
}
errorCodes := map[string]bool{
"401": true,
"500": true,
}
if errorCodes[strconv.Itoa(resp.StatusCode)] {
type Err struct {
Error struct {
Code int `json:"code"`
Message string `json:"message"`
} `json:"error"`
}
data := &Err{}
if err := json.Unmarshal(body, data); err != nil {
return err
}
fmt.Println(data.Error.Message)
apiError = errors.New(string(data.Error.Message))
return apiError
}
apiError = errors.New(string(body))
return apiError
}