This repository has been archived by the owner on May 13, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.go
200 lines (153 loc) · 4.55 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
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
/*
Package shikimori
# Authentication
OAuth2 is used for authentication. [OAuth2 guide].
# Restrictions
API access is limited by `5rps` and `90rpm`.
# Requirements
Add your Oauth2 Application name to [API.UserAgent] requests header.
Don’t mimic a browser.
Your IP address may be banned if you use API without properly set [API.UserAgent] header.
# Pagination in API
When you request N elements from paginated API, you will get N+1 results if API has next page.
[OAuth2 guide]: https://shikimori.me/oauth
*/
package shikimori
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"time"
"github.com/SevereCloud/shikimori/internal"
)
type UnknownError struct {
Status int
Body string
}
func (e UnknownError) Error() string {
return fmt.Sprintf("shikimori: %d %s", e.Status, e.Body)
}
type NotFoundError struct{}
func (e NotFoundError) Error() string {
return "shikimori: Not found"
}
type TooManyRequestsError struct{}
func (e TooManyRequestsError) Error() string {
return "shikimori: 429 Retry later"
}
type UnprocessableEntityErrors []string
func (e UnprocessableEntityErrors) Error() string {
return fmt.Sprintf("shikimori: unprocessable entity: %v", []string(e))
}
const (
rps = 5
rpm = 90
infelicity = time.Millisecond * 100
)
type API struct {
Client *http.Client
BaseURL string
UserAgent string
AccessToken string
limits *internal.Limits
}
func NewAPI() *API {
return &API{
BaseURL: "https://shikimori.me/api/",
UserAgent: "Go-http-client/1.1 (+https://github.com/SevereCloud/shikimori)",
AccessToken: "",
Client: http.DefaultClient,
limits: internal.NewLimits(
internal.NewLimit(rps, time.Second+infelicity),
internal.NewLimit(rpm, time.Minute+infelicity),
),
}
}
func (s *API) buildRequest(ctx context.Context, method string, path string, params interface{}) (*http.Request, error) {
url := s.BaseURL + path
buf := new(bytes.Buffer)
err := json.NewEncoder(buf).Encode(params)
if err != nil {
return nil, fmt.Errorf("shikimori: encode: %w", err)
}
req, err := http.NewRequestWithContext(ctx, method, url, buf)
if err != nil {
return nil, fmt.Errorf("shikimori: build request: %w", err)
}
req.Header.Set("User-Agent", s.UserAgent)
req.Header.Set("Content-Type", "application/json")
if s.AccessToken != "" {
req.Header.Set("Authorization", "Bearer "+s.AccessToken)
}
return req, nil
}
func (s *API) request(ctx context.Context, obj interface{}, method string, path string, params interface{}) error {
req, err := s.buildRequest(ctx, method, path, params)
if err != nil {
return err
}
err = s.limits.RateLimit(ctx)
if err != nil {
return fmt.Errorf("shikimori: %w", err)
}
resp, err := s.Client.Do(req)
if err != nil {
return fmt.Errorf("shikimori: do request: %w", err)
}
defer resp.Body.Close()
dec := json.NewDecoder(resp.Body)
err = s.handleStatus(resp, dec)
if err != nil {
return err
}
err = dec.Decode(&obj)
if err != nil {
return fmt.Errorf("shikimori decode: %w", err)
}
return nil
}
func (*API) handleStatus(resp *http.Response, dec *json.Decoder) error {
switch resp.StatusCode {
case http.StatusOK:
break
case http.StatusUnprocessableEntity:
var errUnprocessableEntity UnprocessableEntityErrors
err := dec.Decode(&errUnprocessableEntity)
if err != nil {
return fmt.Errorf("shikimori: decode 422 error: %w", err)
}
return &errUnprocessableEntity
case http.StatusNotFound:
return &NotFoundError{}
case http.StatusTooManyRequests:
return &TooManyRequestsError{}
default:
bytes, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("shikimori: decode %d error: %w", resp.StatusCode, err)
}
return &UnknownError{
Status: resp.StatusCode,
Body: string(bytes),
}
}
return nil
}
func (s *API) get(ctx context.Context, obj interface{}, path string, params interface{}) error {
return s.request(ctx, obj, http.MethodGet, path, params)
}
// func (s *API) post(ctx context.Context, obj interface{}, path string, params interface{}) error {
// return s.request(ctx, obj, http.MethodPost, path, params)
// }
// func (s *API) put(ctx context.Context, obj interface{}, path string, params interface{}) error {
// return s.request(ctx, obj, http.MethodPut, path, params)
// }
// func (s *API) patch(ctx context.Context, obj interface{}, path string, params interface{}) error {
// return s.request(ctx, obj, http.MethodPatch, path, params)
// }
// func (s *API) delete(ctx context.Context, obj interface{}, path string, params interface{}) error {
// return s.request(ctx, obj, http.MethodDelete, path, params)
// }