-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.go
More file actions
118 lines (96 loc) · 2.5 KB
/
client.go
File metadata and controls
118 lines (96 loc) · 2.5 KB
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
package eodhistoricaldata
import (
"time"
"github.com/go-resty/resty/v2"
"github.com/pkg/errors"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
// Config for create new API client
type Config struct {
HTTPClient *resty.Client
Logger *zap.Logger
APIToken string
FMTFromat string
Debug bool
RetryCount *int
RetryWaitTime *time.Duration
Timeout int
}
// APIClient ...
type APIClient struct {
Stock *Stock
Exchange *Exchange
Fundamental *Fundamental
Logger *zap.Logger
Debug bool
}
// Core params
const (
APIURL = "https://eodhistoricaldata.com/api"
apiDefaultToken = "demo"
fmtFromat = "json"
apiDefaultTimeout = 25
)
// NewAPIClient creates a new API client
func NewAPIClient(cfg Config) (*APIClient, error) {
APIClient := &APIClient{Logger: cfg.Logger, Debug: cfg.Debug}
if APIClient.Logger == nil {
logger, err := createNewLogger()
if err != nil {
return nil, errors.Wrap(err, "Error create new zap logger")
}
APIClient.Logger = logger
}
// Check set timeout param
if cfg.Timeout == 0 {
cfg.Timeout = apiDefaultTimeout
}
if len(cfg.FMTFromat) == 0 {
cfg.FMTFromat = fmtFromat
}
if len(cfg.APIToken) == 0 {
cfg.APIToken = apiDefaultToken
}
// Init rest client (resty)
if cfg.HTTPClient == nil {
cfg.HTTPClient = resty.New()
}
cfg.HTTPClient.SetDebug(APIClient.Debug)
cfg.HTTPClient.SetTimeout(time.Duration(cfg.Timeout) * time.Second)
cfg.HTTPClient.SetHostURL(APIURL)
HTTPClient := &HTTPClient{
client: cfg.HTTPClient,
apiToken: cfg.APIToken,
fmtFromat: cfg.FMTFromat,
logger: APIClient.Logger,
}
if cfg.RetryCount != nil {
HTTPClient.retryCount = cfg.RetryCount
}
if cfg.RetryWaitTime != nil {
HTTPClient.retryWaitTime = cfg.RetryWaitTime
}
if HTTPClient.retryCount == nil || *HTTPClient.retryCount == 0 {
retryCount := 1
HTTPClient.retryCount = &retryCount
}
if HTTPClient.retryWaitTime == nil || *HTTPClient.retryWaitTime == 0 {
retryWaitTime := 1 * time.Second
HTTPClient.retryWaitTime = &retryWaitTime
}
APIClient.Stock = &Stock{Client: HTTPClient}
APIClient.Exchange = &Exchange{Client: HTTPClient}
APIClient.Fundamental = &Fundamental{Client: HTTPClient}
return APIClient, nil
}
// Create new logger
func createNewLogger() (*zap.Logger, error) {
cfg := zap.NewProductionConfig()
cfg.EncoderConfig.EncodeTime = zapcore.RFC3339TimeEncoder
logger, err := cfg.Build()
if err != nil {
return nil, errors.Wrap(err, "Logger Error: init")
}
return logger, nil
}