forked from vickxxx/appstore
-
Notifications
You must be signed in to change notification settings - Fork 3
/
http.go
216 lines (189 loc) · 5.48 KB
/
http.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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
package appstore
import (
"bytes"
"compress/gzip"
"context"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"strings"
)
const ResponseContentTypeJson = "application/json; charset=utf-8"
const ResponseContentTypeGzip = "application/a-gzip"
//NewDefaultHttpClient create new http client
func NewDefaultHttpClient() *http.Client {
tr := &http.Transport{
MaxIdleConns: AppStoreConnectAPIHttpMaxIdleConnection,
IdleConnTimeout: AppStoreConnectAPIHttpIdleConnectionTimeout,
}
return &http.Client{Transport: tr}
}
//RequestBuilder handler
type RequestBuilder struct {
cfg *Config
token *AuthToken
}
//isValidToken method
func (rb *RequestBuilder) isValidToken() bool {
return rb.token.IsValid()
}
//buildUri method
func (rb *RequestBuilder) buildUri(path string, query map[string]interface{}) (uri *url.URL, err error) {
u, err := url.Parse(rb.cfg.Uri)
if err != nil {
return nil, fmt.Errorf("RequestBuilder.buildUri parse: %v", err)
}
u.Path = "/" + path
u.RawQuery = rb.buildQueryParams(query)
return u, err
}
//buildQueryParams method
func (rb *RequestBuilder) buildQueryParams(query map[string]interface{}) string {
q := url.Values{}
if query != nil {
for k, v := range query {
q.Set(k, fmt.Sprintf("%v", v))
}
}
return q.Encode()
}
//buildHeaders method
func (rb *RequestBuilder) buildHeaders() http.Header {
headers := http.Header{}
headers.Set("Accept", "application/a-gzip")
headers.Set("Accept-Encoding", "gzip")
headers.Set("Authorization", "Bearer "+rb.token.Token)
return headers
}
//BuildRequest method
func (rb *RequestBuilder) BuildRequest(ctx context.Context, method string, path string, query map[string]interface{}, body map[string]interface{}) (req *http.Request, err error) {
method = strings.ToUpper(method)
//build uri
uri, err := rb.buildUri(path, query)
if err != nil {
return nil, fmt.Errorf("transport.request build uri: %v", err)
}
//build request
req, err = http.NewRequestWithContext(ctx, method, uri.String(), nil)
if err != nil {
return nil, fmt.Errorf("transport.request new request error: %v", err)
}
//build headers
req.Header = rb.buildHeaders()
return req, nil
}
//NewHttpTransport create new http transport
func NewHttpTransport(config *Config, token *AuthToken, h *http.Client) *Transport {
if h == nil {
h = NewDefaultHttpClient()
}
rb := &RequestBuilder{cfg: config, token: token}
return &Transport{http: h, rb: rb}
}
//Transport wrapper
type Transport struct {
http *http.Client
rb *RequestBuilder
}
//SendRequest method
func (t *Transport) SendRequest(ctx context.Context, method string, path string, query map[string]interface{}, body map[string]interface{}) (resp *http.Response, err error) {
if !t.rb.isValidToken() {
return nil, fmt.Errorf("transport.request invalid token: %v", err)
}
req, err := t.rb.BuildRequest(ctx, method, path, query, body)
if err != nil {
return nil, fmt.Errorf("transport.SendRequest: %v", err)
}
return t.http.Do(req)
}
//Get method
func (t *Transport) Get(ctx context.Context, path string, query map[string]interface{}) (resp *http.Response, err error) {
return t.SendRequest(ctx, http.MethodGet, path, query, nil)
}
//ResponseBody struct
type ResponseBody struct {
status int
//ErrorResult Information with error details that an API returns in the response body whenever the API request is not successful.
// .see https://developer.apple.com/documentation/appstoreconnectapi/errorresponse
Errors []*Error `json:"errors,omitempty"`
}
//GetError method
func (r *ResponseBody) GetError() string {
err := ""
if len(r.Errors) > 0 {
err = r.Errors[0].Detail
}
return err
}
//IsSuccess method
func (r *ResponseBody) IsSuccess() bool {
return r.status < http.StatusMultipleChoices
}
type ResponseHandlerInterface interface {
ReadBody(resp *http.Response) ([]byte, error)
UnmarshalBody(data []byte, v interface{}) error
RestoreBody(data []byte) (io.ReadCloser, error)
}
type ResponseHandlerJson struct {
}
func (r *ResponseHandlerJson) ReadBody(resp *http.Response) ([]byte, error) {
defer resp.Body.Close()
return ioutil.ReadAll(resp.Body)
}
func (r *ResponseHandlerJson) UnmarshalBody(data []byte, v interface{}) error {
return json.Unmarshal(data, &v)
}
func (r *ResponseHandlerJson) RestoreBody(data []byte) (io.ReadCloser, error) {
return ioutil.NopCloser(bytes.NewBuffer(data)), nil
}
type ResponseHandlerGzip struct {
FilterLines bool
}
func (r *ResponseHandlerGzip) ReadBody(resp *http.Response) ([]byte, error) {
defer resp.Body.Close()
zr, err := gzip.NewReader(resp.Body)
if err != nil {
return nil, err
}
defer zr.Close()
return ioutil.ReadAll(zr)
}
func (r *ResponseHandlerGzip) UnmarshalBody(data []byte, v interface{}) error {
if r.FilterLines {
return UnmarshalCSVWithFilterLines(data, v)
} else {
return UnmarshalCSV(data, v)
}
}
func (r *ResponseHandlerGzip) RestoreBody(data []byte) (io.ReadCloser, error) {
var b bytes.Buffer
gz := gzip.NewWriter(&b)
_, err := gz.Write(data)
if err != nil {
return nil, err
}
if err = gz.Flush(); err != nil {
return nil, err
}
if err = gz.Close(); err != nil {
return nil, err
}
return ioutil.NopCloser(bytes.NewBuffer(b.Bytes())), nil
}
func NewResponseHandler(contentType string, filterLines bool) ResponseHandlerInterface {
var handler ResponseHandlerInterface
switch contentType {
case ResponseContentTypeGzip:
handler = &ResponseHandlerGzip{FilterLines: filterLines}
break
case ResponseContentTypeJson:
handler = &ResponseHandlerJson{}
break
default:
handler = &ResponseHandlerJson{}
}
return handler
}