-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathclient.go
189 lines (165 loc) · 4.21 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
/*
идея логики клиента принадлежит https://github.com/adshao
и его проекту https://github.com/adshao/go-binance
*/
package finam
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
)
const (
libraryName = "FINAM-REST API GO"
libraryVersion = "0.0.3"
baseAPIMainURL = "https://trade-api.finam.ru/"
headerKey = "X-Api-Key"
)
// getAPIEndpoint return the base endpoint of the Rest API according the UseDevelop flag
func getAPIEndpoint() string {
//if UseDevelop {
// return baseAPITestnetURL
//}
return baseAPIMainURL
}
// NewClient создание нового клиента
func NewClient(token, clientId string) *Client {
return &Client{
token: token,
clientId: clientId,
BaseURL: getAPIEndpoint(),
UserAgent: "Finam/golang",
HTTPClient: http.DefaultClient,
Logger: log.New(os.Stderr, "go-finam ", log.LstdFlags),
}
}
// Client define API client
type Client struct {
token string
clientId string
BaseURL string
UserAgent string
HTTPClient *http.Client
Debug bool
Logger *log.Logger
TimeOffset int64
}
func (c *Client) debug(format string, v ...interface{}) {
if c.Debug {
c.Logger.Printf(format, v...)
}
}
func (c *Client) parseRequest(r *request, opts ...RequestOption) (err error) {
// set request options from user
for _, opt := range opts {
opt(r)
}
err = r.validate()
if err != nil {
return err
}
fullURL := fmt.Sprintf("%s%s", c.BaseURL, r.endpoint)
queryString := r.query.Encode()
//body := &bytes.Buffer{}
header := http.Header{}
if r.header != nil {
header = r.header.Clone()
}
//c.debug("start header: %s", r.header)
if r.body != nil {
//header.Set("Content-Type", "application/json")
c.debug("r.body: %s", r.body)
}
bodyString := r.form.Encode()
if bodyString != "" {
header.Set("Content-Type", "application/x-www-form-urlencoded")
r.body = bytes.NewBufferString(bodyString)
//body = bytes.NewBufferString(bodyString)
c.debug("bodyString: %s", bodyString)
}
if c.token != "" {
//header.Set("X-Api-Key", c.token)
header.Set(headerKey, c.token)
}
c.debug("header: %s", header)
if queryString != "" {
fullURL = fmt.Sprintf("%s?%s", fullURL, queryString)
}
//c.debug("full url: %s, body: %s", fullURL, bodyString)
c.debug("full url: %s", fullURL)
r.fullURL = fullURL
r.header = header
//r.body = body
return nil
}
func (c *Client) callAPI(ctx context.Context, r *request, opts ...RequestOption) (data []byte, err error) {
err = c.parseRequest(r, opts...)
if err != nil {
return []byte{}, err
}
req, err := http.NewRequest(r.method, r.fullURL, r.body)
if err != nil {
return []byte{}, err
}
req = req.WithContext(ctx)
req.Header = r.header
c.debug("request: %#v", req)
//f := c.do
//if f == nil {
// f = c.HTTPClient.Do
//}
//res, err := f(req)
res, err := c.HTTPClient.Do(req)
if err != nil {
return []byte{}, err
}
data, err = io.ReadAll(res.Body)
if err != nil {
return []byte{}, err
}
defer func() {
cerr := res.Body.Close()
// Only overwrite the retured error if the original error was nil and an
// error occurred while closing the body.
if err == nil && cerr != nil {
err = cerr
}
}()
c.debug("response: %#v", res)
c.debug("response body: %s", string(data))
c.debug("response status code: %d", res.StatusCode)
// из финама приходит другая структура ошибки
if res.StatusCode >= http.StatusBadRequest {
apiErr := new(APIError)
e := json.Unmarshal(data, apiErr)
if e != nil {
c.debug("failed to unmarshal json: %s", e)
}
return nil, apiErr
}
return data, nil
}
// структура ошибки
type ResponseError struct {
Code string `json:"code"`
Message string `json:"message"`
Data interface{} `json:"data"`
}
type APIError struct {
ResponseError ResponseError `json:"error"`
}
func (e APIError) Error() string {
return fmt.Sprintf("<APIError> code=%s, msg=%s, data=%s", e.ResponseError.Code, e.ResponseError.Message, e.ResponseError.Data)
}
func IsAPIError(e error) bool {
_, ok := e.(*APIError)
return ok
}
// (debug) вернем текущую версию
func (c *Client) Version() string {
return libraryName + " v." + libraryVersion
}