-
Notifications
You must be signed in to change notification settings - Fork 0
/
discogs.go
89 lines (74 loc) · 1.69 KB
/
discogs.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
package discogs
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"time"
)
const (
BaseURL = "https://api.discogs.com"
)
// Client .
type Client struct {
apiKey string
baseURL string
userAgent string
HTTPClient *http.Client
}
// NewClient .
func NewClient(apiKey string) *Client {
return &Client{
apiKey: apiKey,
HTTPClient: &http.Client{
Timeout: 5 * time.Minute,
},
baseURL: BaseURL,
}
}
type errorResponse struct {
Code int `json:"code"`
Message string `json:"message"`
}
type successResponse struct {
Code int `json:"code"`
Data interface{} `json:"data"`
}
func (c *Client) sendRequest(req *http.Request, v interface{}) error {
req.Header.Set("Accept", "application/json; charset=utf-8")
req.Header.Set("Authorization", fmt.Sprintf("Discogs token=%s", c.apiKey))
// debugging
//dump, err := httputil.DumpRequestOut(req, true)
//if err != nil {
// fmt.Printf(err.Error())
//}
//fmt.Printf("%s\n\n", dump)
res, err := c.HTTPClient.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
// Try to unmarshall into errorResponse
if res.StatusCode != http.StatusOK {
var errRes errorResponse
if err = json.NewDecoder(res.Body).Decode(&errRes); err == nil {
return errors.New(errRes.Message)
}
return fmt.Errorf("unknown error, status code: %d", res.StatusCode)
}
// Unmarshall and populate v
fullResponse := successResponse{
Code: res.StatusCode,
Data: v,
}
// debugging
//if resDump, err := httputil.DumpResponse(res, true); err != nil {
// fmt.Printf(err.Error())
//} else {
// fmt.Printf("%s\n\n", resDump)
//}
if err = json.NewDecoder(res.Body).Decode(&fullResponse.Data); err != nil {
return err
}
return nil
}