-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
239 lines (206 loc) · 6.43 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
// Package alphavantage implements clients and parsers for the
// https://www.alphavantage.co API.
package alphavantage
import (
"bytes"
"context"
"encoding/csv"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"reflect"
"strconv"
"strings"
"time"
"golang.org/x/time/rate"
)
const (
StandardTokenEnvironmentVariableName = "ALPHA_VANTAGE_TOKEN"
)
const DefaultDateFormat = "2006-01-02"
type Client struct {
Limiter interface {
Wait(ctx context.Context) error
}
Client interface {
Do(*http.Request) (*http.Response, error)
}
APIKey string
}
func NewClient(apiKey string) *Client {
return &Client{
Client: http.DefaultClient,
Limiter: rate.NewLimiter(rate.Every(time.Minute/5), 5),
APIKey: apiKey,
}
}
func (client *Client) Do(req *http.Request) (*http.Response, error) {
if client.Client == nil {
client.Client = http.DefaultClient
}
if client.Limiter != nil {
err := client.Limiter.Wait(req.Context())
if err != nil {
return &http.Response{}, err
}
}
q := req.URL.Query()
q.Set("apikey", client.APIKey)
req.URL.RawQuery = q.Encode()
res, err := client.Client.Do(req)
if err != nil {
return nil, err
}
if res.StatusCode >= 300 || res.StatusCode < 200 {
buf, err := io.ReadAll(io.LimitReader(res.Body, 1<<10))
if err != nil {
buf = []byte(err.Error())
}
return res, fmt.Errorf("request failed with status %d %s: %s",
res.StatusCode, http.StatusText(res.StatusCode), string(buf))
}
return res, nil
}
func checkError(rc io.ReadCloser) (io.ReadCloser, error) {
var buf [1]byte
n, err := rc.Read(buf[:])
if err != nil {
return nil, fmt.Errorf("could not read request response: %w", err)
}
mr := io.MultiReader(bytes.NewReader(buf[:]), rc)
if n > 0 && buf[0] == '{' {
var message struct {
Note string `json:"Note,omitempty"`
Information string `json:"Information,omitempty"`
ErrorMessage string `json:"Error Message,omitempty"`
Detail string `json:"detail,omitempty"`
}
err = json.NewDecoder(mr).Decode(&message)
if err != nil {
return nil, fmt.Errorf("could not read response for: %w", err)
}
if strings.Contains(message.Note, " higher API call frequency") {
return nil, fmt.Errorf("reached alphavantage rate limit")
}
if message.ErrorMessage != "" {
return nil, fmt.Errorf("alphavantage request did not return csv; got notice: %w", errors.New(message.ErrorMessage))
}
if message.Detail != "" {
return nil, fmt.Errorf("alphavantage request did not return csv; got notice: %w", errors.New(message.Detail))
}
if message.Note != "" || message.Information != "" {
return nil, fmt.Errorf("alphavantage request did not return csv; got notice: %w", errors.New(strings.Join([]string{message.Note, message.Information}, " ")))
}
return nil, fmt.Errorf("alphavantage request did not return csv")
}
return multiReadCloser{
Reader: mr,
close: rc.Close,
}, nil
}
var typeType = reflect.TypeOf(time.Time{})
// ParseCSV parses rows of data into a slice of structs it only supports decoding into
// fields of type string, int, float64, and time.Time
//
// Struct fields must be tagged with their expected column header with "column-name".
// If there is no mapping for a column to field, that data column is ignored and the struct
// field will remain unset (it will have its zero value).
//
// Fields with type time.Time may use an additional "time-layout" field
// to specify the layout to use with time.ParseInLocation.
// If location is not specified, eastern time is used.
// "null" values in CSV for time are ignored; time keeps its zero value.
func ParseCSV(r io.Reader, data interface{}, location *time.Location) error {
if location == nil {
location = time.UTC
}
rv := reflect.ValueOf(data)
if rv.Kind() != reflect.Ptr {
panic("parse must receive pointer to data")
}
if rv.IsNil() {
panic("parse must not receive pointer to nil data")
}
reader := csv.NewReader(r)
reader.TrimLeadingSpace = true
header, err := reader.Read()
if err != nil {
return err
}
reader.FieldsPerRecord = len(header)
rvt := rv.Type()
switch rvt.Elem().Kind() {
default:
return fmt.Errorf("expected a pointer to an array or slice: got %T", data)
case reflect.Slice:
}
if rvt.Elem().Elem().Kind() != reflect.Struct {
return fmt.Errorf("expected a pointer to an array or slice of structs: got %T", data)
}
columnToField := make(map[int]int, len(header))
structType := rvt.Elem().Elem()
for columnHeaderIndex, columnHeaderName := range header {
for fieldIndex := 0; fieldIndex < structType.NumField(); fieldIndex++ {
fieldType := structType.Field(fieldIndex)
csvTag := fieldType.Tag.Get("column-name")
if csvTag != columnHeaderName {
continue
}
columnToField[columnHeaderIndex] = fieldIndex
}
}
for rowIndex := 1; ; rowIndex++ {
row, err := reader.Read()
if err != nil {
if err == io.EOF {
return nil
}
return err
}
structValue := reflect.New(structType)
for columnIndex, value := range row {
fieldIndex, ok := columnToField[columnIndex]
if !ok {
continue
}
structFieldType := structType.Field(fieldIndex)
switch structFieldType.Type.Kind() {
case reflect.String:
structValue.Elem().Field(fieldIndex).SetString(value)
case reflect.Float64:
fl, err := strconv.ParseFloat(value, 64)
if err != nil {
return fmt.Errorf("failed to parse float64 value %q on row %d column %d (%s): %w", value, rowIndex, columnIndex, header[columnIndex], err)
}
structValue.Elem().Field(fieldIndex).SetFloat(fl)
case reflect.Int:
in, err := strconv.ParseInt(value, 10, 64)
if err != nil {
return fmt.Errorf("failed to parse float64 value %q on row %d column %d (%s): %w", value, rowIndex, columnIndex, header[columnIndex], err)
}
structValue.Elem().Field(fieldIndex).SetInt(in)
default:
if structFieldType.Type != typeType {
return fmt.Errorf("unsupported type %T for field %s", structFieldType.Type, structFieldType.Name)
}
layout := DefaultDateFormat
tagLayout := structFieldType.Tag.Get("time-layout")
if tagLayout != "" {
layout = tagLayout
}
if value == "null" {
continue
}
tm, err := time.ParseInLocation(layout, value, location)
if err != nil {
return fmt.Errorf("failed to parse time value on row %d column %d (%s): %w", rowIndex, columnIndex, header[columnIndex], err)
}
structValue.Elem().Field(fieldIndex).Set(reflect.ValueOf(tm))
}
}
rv.Elem().Set(reflect.Append(rv.Elem(), structValue.Elem()))
}
return nil
}