-
Notifications
You must be signed in to change notification settings - Fork 26
/
discogs.go
121 lines (102 loc) · 2.48 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
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
package discogs
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
)
const (
discogsAPI = "https://api.discogs.com"
)
// Options is a set of options to use discogs API client
type Options struct {
// Discogs API endpoint (optional).
URL string
// Currency to use (optional, default is USD).
Currency string
// UserAgent to to call discogs api with.
UserAgent string
// Token provided by discogs (optional).
Token string
}
// Discogs is an interface for making Discogs API requests.
type Discogs interface {
CollectionService
DatabaseService
MarketPlaceService
SearchService
}
type discogs struct {
CollectionService
DatabaseService
SearchService
MarketPlaceService
}
var header *http.Header
// New returns a new discogs API client.
func New(o *Options) (Discogs, error) {
header = &http.Header{}
if o == nil || o.UserAgent == "" {
return nil, ErrUserAgentInvalid
}
header.Add("User-Agent", o.UserAgent)
cur, err := currency(o.Currency)
if err != nil {
return nil, err
}
// set token, it's required for some queries like search
if o.Token != "" {
header.Add("Authorization", "Discogs token="+o.Token)
}
if o.URL == "" {
o.URL = discogsAPI
}
return discogs{
newCollectionService(o.URL + "/users"),
newDatabaseService(o.URL, cur),
newSearchService(o.URL + "/database/search"),
newMarketPlaceService(o.URL+"/marketplace", cur),
}, nil
}
// currency validates currency for marketplace data.
// Defaults to the authenticated users currency. Must be one of the following:
// USD GBP EUR CAD AUD JPY CHF MXN BRL NZD SEK ZAR
func currency(c string) (string, error) {
switch c {
case "USD", "GBP", "EUR", "CAD", "AUD", "JPY", "CHF", "MXN", "BRL", "NZD", "SEK", "ZAR":
return c, nil
case "":
return "USD", nil
default:
return "", ErrCurrencyNotSupported
}
}
func request(path string, params url.Values, resp interface{}) error {
r, err := http.NewRequest("GET", path+"?"+params.Encode(), nil)
if err != nil {
return err
}
r.Header = *header
client := &http.Client{}
response, err := client.Do(r)
if err != nil {
return err
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
switch response.StatusCode {
case http.StatusUnauthorized:
return ErrUnauthorized
case http.StatusTooManyRequests:
return ErrTooManyRequests
default:
return fmt.Errorf("unknown error: %s", response.Status)
}
}
body, err := ioutil.ReadAll(response.Body)
if err != nil {
return err
}
return json.Unmarshal(body, &resp)
}