/
client.go
324 lines (273 loc) · 7.68 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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
package qstarscli
import (
"bytes"
"context"
"encoding/json"
"errors"
"io"
"io/ioutil"
"net/http/httptest"
"reflect"
"github.com/QOSGroup/qmoon/lib/qstarscli/qstarsmock"
"github.com/google/go-querystring/query"
"github.com/sirupsen/logrus"
"github.com/tendermint/go-amino"
tmltypes "github.com/tendermint/tendermint/rpc/lib/types"
"net/http"
"net/url"
)
var tmDefaultServer = "http://localhost:1317"
var cdc = amino.NewCodec()
// 代码结构和部分实现的灵感来源于 https://github.com/google/go-github
// Option 可选参数
type option struct {
host string
// HTTP Client used to communicate with the API.
// Base URL for API requests. Defaults to the public GitHub API, but can be
// set to a domain endpoint to use with GitHub Enterprise. BaseURL should
// always be specified with a trailing slash.
baseURL *url.URL
}
type SetOption func(options *option) error
// NewOption 创建可选参数
func NewOption(fs ...SetOption) (*option, error) {
opt := &option{
host: tmDefaultServer,
}
baseURL, err := url.Parse(opt.host)
if err != nil {
return nil, err
}
opt.baseURL = baseURL
if fs != nil {
for _, f := range fs {
if err := f(opt); err != nil {
return nil, err
}
}
}
return opt, nil
}
// SetOptionHost 设置可选参数host
func SetOptionHost(host string) SetOption {
return func(opt *option) error {
baseURL, err := url.Parse(host)
if err != nil {
return err
}
opt.host = host
opt.baseURL = baseURL
return nil
}
}
//func MakeCodec() *amino.Codec {
// cdc := amino.NewCodec()
//
// cdc.RegisterInterface((*account.Account)(nil), nil)
// cdc.RegisterConcrete(&qosacc.QOSAccount{}, "qbase/account/QOSAccount", nil)
//
// return cdc
//}
// Client 客户端结构
type Client struct {
host string
baseURL *url.URL
client *http.Client
cdc *amino.Codec
common service // Reuse a single struct instead of allocating one for each service on the heap.
//NodeVersion *nodeVersionService
//Version *versionService
//Accounts *accountsService
//KV *kvService
TransferService *transferService
}
type service struct {
client *Client
}
// NewClient 创建tendermint Client
func NewClient(opt *option) *Client {
if opt == nil {
opt, _ = NewOption()
}
c := &Client{
host: opt.host,
baseURL: opt.baseURL,
client: http.DefaultClient,
cdc: cdc,
}
c.common.client = c
//c.NodeVersion = (*nodeVersionService)(&c.common)
//c.Version = (*versionService)(&c.common)
//c.Accounts = (*accountsService)(&c.common)
//c.KV = (*kvService)(&c.common)
c.TransferService = (*transferService)(&c.common)
return c
}
// addOptions adds the parameters in opt as URL query parameters to s. opt
// must be a struct whose fields may contain "url" tags.
func addOptions(s string, opt interface{}) (string, error) {
v := reflect.ValueOf(opt)
if v.Kind() == reflect.Ptr && v.IsNil() {
return s, nil
}
u, err := url.Parse(s)
if err != nil {
return s, err
}
qs, err := query.Values(opt)
if err != nil {
return s, err
}
u.RawQuery = qs.Encode()
return u.String(), nil
}
// NewRequest creates an API request. A relative URL can be provided in urlStr,
// in which case it is resolved relative to the BaseURL of the Client.
// Relative URLs should always be specified without a preceding slash. If
// specified, the value pointed to by body is JSON encoded and included as the
// request body.
func (c *Client) NewRequest(method, urlStr string, body interface{}) (*http.Request, error) {
u, err := c.baseURL.Parse(urlStr)
if err != nil {
return nil, err
}
var buf io.ReadWriter
if body != nil {
buf = new(bytes.Buffer)
enc := json.NewEncoder(buf)
enc.SetEscapeHTML(false)
err := enc.Encode(body)
if err != nil {
return nil, err
}
}
req, err := http.NewRequest(method, u.String(), buf)
if err != nil {
return nil, err
}
return req, nil
}
// sanitizeURL redacts the client_secret parameter from the URL which may be
// exposed to the user.
func sanitizeURL(uri *url.URL) *url.URL {
if uri == nil {
return nil
}
params := uri.Query()
if len(params.Get("client_secret")) > 0 {
params.Set("client_secret", "REDACTED")
uri.RawQuery = params.Encode()
}
return uri
}
// checkResponse checks the API response for errors, and returns them if
// present. A response is considered an error if it has a status code outside
// the 200 range or equal to 202 Accepted.
// API error responses are expected to have either no response
// body, or a JSON response body that maps to ErrorResponse. Any other
// response body will be silently ignored.
//
// The error type will be *RateLimitError for rate limit exceeded errors,
// *AcceptedError for 202 Accepted status codes,
// and *TwoFactorAuthError for two-factor authentication errors.
func checkResponse(r *http.Response) error {
if c := r.StatusCode; 200 <= c && c <= 299 {
return nil
}
if c := r.StatusCode; c == http.StatusUnauthorized || c == http.StatusForbidden {
return errors.New("没有授权")
}
return nil
}
// Do sends an API request and returns the API response. The API response is
// JSON decoded and stored in the value pointed to by v, or returned as an
// error if an API error has occurred. If v implements the io.Writer
// interface, the raw response body will be written to v, without attempting to
// first decode it. If rate limit is exceeded and reset time is in the future,
// Do returns *RateLimitError immediately without making a network API call.
//
// The provided ctx must be non-nil. If it is canceled or times out,
// ctx.Err() will be returned.
func (c *Client) Do(ctx context.Context, req *http.Request, v interface{}) (*http.Response, error) {
if ctx == nil {
ctx = context.Background()
}
req = req.WithContext(ctx)
resp, err := c.client.Do(req)
if err != nil {
// If we got an error, and the context has been canceled,
// the context's error is probably more useful.
select {
case <-ctx.Done():
return nil, ctx.Err()
default:
}
// If the error type is *url.Error, sanitize its URL before returning.
if e, ok := err.(*url.Error); ok {
if url, err := url.Parse(e.URL); err == nil {
e.URL = sanitizeURL(url).String()
return nil, e
}
}
return nil, err
}
defer func() {
// Drain up to 512 bytes and close the body to let the Transport reuse the connection
io.CopyN(ioutil.Discard, resp.Body, 512)
resp.Body.Close()
}()
err = checkResponse(resp)
if err != nil {
// even though there was an error, we still return the response
// in case the caller wants to inspect it further
return resp, err
}
if v != nil {
if w, ok := v.(io.Writer); ok {
io.Copy(w, resp.Body)
} else {
var tmresp tmltypes.RPCResponse
//body, err := ioutil.ReadAll(resp.Body)
//logrus.WithField("req", req.RequestURI).WithField("body", string(body)).WithField("err", err).Debugln()
//if err != nil {
// return resp, err
//}
//fmt.Println(string(body))
//err = json.Unmarshal(body, &tmresp)
err = json.NewDecoder(resp.Body).Decode(&tmresp)
if err != nil {
if err == io.EOF {
err = nil // ignore EOF errors caused by empty response body
} else {
return resp, err
}
}
if tmresp.Error != nil {
return resp, tmresp.Error
}
err = c.cdc.UnmarshalJSON(tmresp.Result, v)
logrus.WithField("model", "qstarscli").
WithField("result", string(tmresp.Result)).
WithField("err", err).
Debugln()
if err != nil {
return resp, err
}
}
}
return resp, err
}
type testQstarsServer struct {
s *httptest.Server
}
func (tq *testQstarsServer) Close() {
tq.s.Close()
}
func NewTestQstarsServer() *testQstarsServer {
tq := &testQstarsServer{}
tm := qstarsmock.NewQstarsMock()
s := httptest.NewServer(tm)
tmDefaultServer = s.URL
tq.s = s
return tq
}