-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathapi.go
71 lines (58 loc) · 1.41 KB
/
api.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
package spark
import (
"bytes"
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/url"
)
var httpClient *http.Client
func init() {
httpClient = &http.Client{}
}
func (s *Spark) request(req *http.Request) ([]byte, error) {
// set headers for all requests
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", s.token))
req.Header.Set("Content-Type", "application/json; charset=utf-8")
res, err := httpClient.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
bs, err := ioutil.ReadAll(res.Body)
// return code should be 200
if res.StatusCode != http.StatusOK {
// spark delete is exit code 204 "No Content"
if res.StatusCode != 204 {
e := fmt.Sprintf("HTTP Status Code: %d\n%s", res.StatusCode, string(bs))
return nil, errors.New(e)
}
}
return bs, err
}
func (s *Spark) GetRequest(url string, uv *url.Values) ([]byte, error) {
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
if uv != nil {
req.URL.RawQuery = (*uv).Encode()
}
return s.request(req)
}
func (s *Spark) PostRequest(url string, body *bytes.Buffer) ([]byte, error) {
req, err := http.NewRequest("POST", url, body)
if err != nil {
return nil, err
}
return s.request(req)
}
func (s *Spark) DeleteRequest(url string) ([]byte, error) {
fmt.Println("Delete url: ", url)
req, err := http.NewRequest("DELETE", url, nil)
if err != nil {
return nil, err
}
return s.request(req)
}