-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
66 lines (54 loc) · 1.35 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
package spotify
import (
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"time"
)
type Client struct {
AccessToken string
RefreshToken string
ClientId string
ClientSecret string
}
func (c *Client) get(url string, body io.Reader) ([]byte, error) {
return c.fetch("GET", url, body)
}
func (c *Client) post(url string, body io.Reader) ([]byte, error) {
return c.fetch("POST", url, body)
}
func (c *Client) put(url string, body io.Reader) ([]byte, error) {
return c.fetch("PUT", url, body)
}
func (c *Client) delete(url string, body io.Reader) ([]byte, error) {
return c.fetch("DELETE", url, body)
}
func (c *Client) fetch(method string, url string, body io.Reader) ([]byte, error) {
client := &http.Client{Timeout: time.Second * 5}
request, err := http.NewRequest(method, url, body)
if err != nil {
return []byte{}, err
}
request.Header.Add("Authorization", fmt.Sprintf("Bearer %s", c.AccessToken))
resp, err := client.Do(request)
if err != nil {
return []byte{}, err
}
defer resp.Body.Close()
bytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return []byte{}, err
}
var result map[string]interface{}
err = json.Unmarshal(bytes, &result)
if err != nil {
return []byte{}, err
}
if result["error"] != nil {
return []byte{}, errors.New(fmt.Sprintf("%s", result["error_description"]))
}
return bytes, nil
}