-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.go
214 lines (177 loc) · 4.81 KB
/
client.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
package apidq
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"strings"
"time"
"github.com/pkg/errors"
)
const (
BaseURL = "https://api.apidq.io/"
contentTypeJSON = "application/json"
acceptJSON = "application/json"
authorization = "Authorization"
ServiceAddress = "address"
ServicePhone = "phone"
ServiceName = "name"
ctxKeyService ctxKey = iota
)
type ctxKey int
type service struct {
client *Client
}
func (s *service) prepareCtx(ctx context.Context, service string) context.Context {
return context.WithValue(ctx, ctxKeyService, service)
}
func (s *service) post(ctx context.Context, service, url string, req, rsp interface{}) (*http.Response, error) {
ctx = s.prepareCtx(ctx, service)
r, err := s.client.newRequest(ctx, http.MethodPost, url, contentTypeJSON, req)
if err != nil {
return nil, err
}
httpRsp, err := s.client.do(ctx, r, rsp)
if err != nil {
return httpRsp, err
}
return httpRsp, nil
}
type RequestOptionFunc func(r *http.Request) error
type Client struct {
baseURL *url.URL
client *http.Client
common service
Address *AddressService
Phone *PhoneService
Name *NameService
requestOptions []RequestOptionFunc
}
func NewClient(httpClient *http.Client, baseURL string, reqOpts ...RequestOptionFunc) (*Client, error) {
if httpClient == nil {
httpClient = &http.Client{
Transport: http.DefaultTransport,
Timeout: 15 * time.Second,
}
}
if baseURL == "" {
baseURL = BaseURL
}
pBaseURL, err := url.Parse(baseURL)
if err != nil {
return nil, err
}
c := &Client{client: httpClient, baseURL: pBaseURL, requestOptions: reqOpts}
c.common.client = c
c.Address = &AddressService{&c.common}
c.Phone = &PhoneService{&c.common}
c.Name = &NameService{&c.common}
return c, nil
}
// WithAuthService ApiDQ дает возможность генерировать отдельные токены для всех сервисов.
// Допустимые значения service = ["address","phone","name"]
func (c *Client) WithAuthService(apiKey, service string) *Client {
c.requestOptions = append(c.requestOptions, func(r *http.Request) error {
if strings.Contains(fmt.Sprintf("%v", r.Context().Value(ctxKeyService)), service) {
r.Header.Set(authorization, apiKey)
}
return nil
})
return c
}
// WithAuth Auth for all services
func (c *Client) WithAuth(apiKey string) *Client {
c.requestOptions = append(c.requestOptions, func(r *http.Request) error {
r.Header.Set(authorization, apiKey)
return nil
})
return c
}
// WithReqOptions Add request options
func (c *Client) WithReqOptions(reqOpts ...RequestOptionFunc) *Client {
c.requestOptions = append(c.requestOptions, reqOpts...)
return c
}
func (c *Client) newRequest(ctx context.Context, method, url, contentType string, body interface{}) (*http.Request, error) {
u, err := c.baseURL.Parse(url)
if err != nil {
return nil, err
}
var buf io.ReadWriter
if body != nil {
if method == http.MethodPost {
buf = &bytes.Buffer{}
enc := json.NewEncoder(buf)
errEnc := enc.Encode(body)
if errEnc != nil {
return nil, errEnc
}
} else {
return nil, fmt.Errorf("request Method \"%q\" is unknown", method)
}
}
req, err := http.NewRequestWithContext(ctx, method, u.String(), buf)
if err != nil {
return nil, err
}
if body != nil {
req.Header.Set("Content-Type", contentType)
req.Header.Set("Accept", acceptJSON)
}
for _, opt := range c.requestOptions {
if errOpt := opt(req); errOpt != nil {
return nil, errOpt
}
}
return req, nil
}
// Отправка запроса
func (c *Client) do(_ context.Context, req *http.Request, v interface{}) (rsp *http.Response, err error) {
rsp, err = c.client.Do(req)
if err != nil {
return nil, err
}
defer func() {
if rsp != nil && rsp.Body != nil {
if e := rsp.Body.Close(); e != nil && err == nil {
err = e // if body not close, return err
}
}
}()
if v != nil && rsp.ContentLength != 0 {
body, e := ioutil.ReadAll(rsp.Body)
if e != nil {
return nil, e
}
if rsp.StatusCode != 200 {
errRsp := &ErrorResponse{}
decErr := json.Unmarshal(body, errRsp)
if decErr == nil && errRsp.Code != 0 && errRsp.Message != "" {
return nil, errRsp
}
if decErr == nil {
decErr = errors.New("invalid ErrorResponse struct")
}
return nil, errors.WithMessage(decErr, string(body))
}
decErr := json.Unmarshal(body, v)
if decErr == nil {
return rsp, nil
}
return nil, errors.WithMessage(decErr, string(body))
}
return rsp, nil
}
type ErrorResponse struct {
Message string `json:"message"`
// https://grpc.github.io/grpc/core/md_doc_statuscodes.html
// https://developers.google.com/maps-booking/reference/grpc-api/status_codes
Code int `json:"code"`
}
func (e ErrorResponse) Error() string {
return fmt.Sprintf("[%d] %s", e.Code, e.Message)
}