forked from wtfutil/wtf
/
client.go
80 lines (64 loc) · 1.53 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
package finnhub
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
)
// Client ..
type Client struct {
symbols []string
apiKey string
}
// NewClient ..
func NewClient(symbols []string, apiKey string) *Client {
client := Client{
symbols: symbols,
apiKey: apiKey,
}
return &client
}
// Getquote ..
func (client *Client) Getquote() ([]Quote, error) {
quotes := []Quote{}
for _, s := range client.symbols {
resp, err := client.finnhubRequest(s)
if err != nil {
return quotes, err
}
var quote Quote
quote.Stock = s
err = json.NewDecoder(resp.Body).Decode("e)
if err != nil {
return quotes, err
}
quotes = append(quotes, quote)
}
return quotes, nil
}
/* -------------------- Unexported Functions -------------------- */
var (
finnhubURL = &url.URL{Scheme: "https", Host: "finnhub.io", Path: "/api/v1/quote"}
)
func (client *Client) finnhubRequest(symbol string) (*http.Response, error) {
params := url.Values{}
params.Add("symbol", symbol)
params.Add("token", client.apiKey)
url := finnhubURL.ResolveReference(&url.URL{RawQuery: params.Encode()})
req, err := http.NewRequest("GET", url.String(), http.NoBody)
req.Header.Add("Accept", "application/json")
req.Header.Add("Content-Type", "application/json")
if err != nil {
return nil, err
}
httpClient := &http.Client{}
resp, err := httpClient.Do(req)
if err != nil {
return nil, err
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
return nil, fmt.Errorf(resp.Status)
}
return resp, nil
}