-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathrequest.go
85 lines (71 loc) · 1.96 KB
/
request.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
package jpush
import (
"context"
"encoding/json"
"io"
"strconv"
"github.com/LyricTian/req"
)
// Error 错误
type Error struct {
StatusCode int `json:"status_code"`
ErrorItem *ErrorItem `json:"error,omitempty"`
HeaderItem *HeaderItem `json:"header,omitempty"`
}
func (e *Error) Error() string {
buf, _ := json.MarshalIndent(e, "", " ")
return string(buf)
}
// NewErrorItem 创建错误项实例
func NewErrorItem(code int, message string) *ErrorItem {
return &ErrorItem{
Code: code,
Message: message,
}
}
// ErrorItem 错误项
type ErrorItem struct {
Code int `json:"code"`
Message string `json:"message"`
}
// HeaderItem 响应头
type HeaderItem struct {
XRateLimitQuota int `json:"X-Rate-Limit-Quota"`
XRateLimitRemaining int `json:"X-Rate-Limit-Remaining"`
XRateLimitReset int `json:"X-Rate-Limit-Reset"`
}
// jpush request
func pushRequest(ctx context.Context, opts *options, router, method string, body io.Reader) (req.Responser, error) {
urlStr := req.RequestURL(opts.host, router)
resp, err := req.Do(ctx, urlStr, method, body, req.SetBasicAuth(opts.appKey, opts.masterSecret))
if err != nil {
return nil, err
} else if code := resp.StatusCode(); code != 200 {
e := &Error{
StatusCode: code,
}
var result struct {
Error *ErrorItem `json:"error"`
}
buf, err := resp.Bytes()
if err != nil {
e.ErrorItem = NewErrorItem(0, err.Error())
return nil, e
}
err = json.Unmarshal(buf, &result)
if err != nil {
e.ErrorItem = NewErrorItem(0, string(buf))
return nil, e
}
e.ErrorItem = result.Error
if code == 429 {
header := new(HeaderItem)
header.XRateLimitQuota, _ = strconv.Atoi(resp.Response().Header.Get("X-Rate-Limit-Quota"))
header.XRateLimitRemaining, _ = strconv.Atoi(resp.Response().Header.Get("X-Rate-Limit-Remaining"))
header.XRateLimitReset, _ = strconv.Atoi(resp.Response().Header.Get("X-Rate-Limit-Reset"))
e.HeaderItem = header
}
return nil, e
}
return resp, nil
}