This repository has been archived by the owner on Aug 12, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
api.go
171 lines (152 loc) · 4.79 KB
/
api.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
/*
Package kumex provides two kinds of APIs: `RESTful API` and `WebSocket feed`.
The official document: https://docs.kumex.com
*/
package kumex
import (
"bytes"
"errors"
"fmt"
"log"
"os"
"runtime"
"time"
"github.com/sirupsen/logrus"
)
var (
// Version is SDK version.
Version = "1.0.4"
// DebugMode will record the logs of API and WebSocket to files in the directory "kumex.LogDirectory" according to the minimum log level "kumex.LogLevel".
DebugMode = os.Getenv("API_DEBUG_MODE") == "1"
)
func init() {
// Initialize the logging component by default
logrus.SetLevel(logrus.DebugLevel)
if runtime.GOOS == "windows" {
SetLoggerDirectory("tmp")
} else {
SetLoggerDirectory("/tmp")
}
}
// SetLoggerDirectory sets the directory for logrus output.
func SetLoggerDirectory(directory string) {
var logFile string
if !DebugMode {
logFile = os.DevNull
} else {
logFile = fmt.Sprintf("%s/kucoin-sdk-%s.log", directory, time.Now().Format("2006-01-02"))
}
logWriter, err := os.OpenFile(logFile, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0664)
if err != nil {
log.Panicf("Open file failed: %s", err.Error())
}
logrus.SetOutput(logWriter)
}
// An ApiService provides a HTTP client and a signer to make a HTTP request with the signature to KuCoin API.
type ApiService struct {
apiBaseURI string
apiKey string
apiSecret string
apiPassphrase string
apiSkipVerifyTls bool
requester Requester
signer Signer
}
// ProductionApiBaseURI is api base uri for production.
const ProductionApiBaseURI = "https://api.kumex.com"
// An ApiServiceOption is a option parameter to create the instance of ApiService.
type ApiServiceOption func(service *ApiService)
// ApiBaseURIOption creates a instance of ApiServiceOption about apiBaseURI.
func ApiBaseURIOption(uri string) ApiServiceOption {
return func(service *ApiService) {
service.apiBaseURI = uri
}
}
// ApiKeyOption creates a instance of ApiServiceOption about apiKey.
func ApiKeyOption(key string) ApiServiceOption {
return func(service *ApiService) {
service.apiKey = key
}
}
// ApiSecretOption creates a instance of ApiServiceOption about apiSecret.
func ApiSecretOption(secret string) ApiServiceOption {
return func(service *ApiService) {
service.apiSecret = secret
}
}
// ApiPassPhraseOption creates a instance of ApiServiceOption about apiPassPhrase.
func ApiPassPhraseOption(passPhrase string) ApiServiceOption {
return func(service *ApiService) {
service.apiPassphrase = passPhrase
}
}
// ApiSkipVerifyTlsOption creates a instance of ApiServiceOption about apiSkipVerifyTls.
func ApiSkipVerifyTlsOption(skipVerifyTls bool) ApiServiceOption {
return func(service *ApiService) {
service.apiSkipVerifyTls = skipVerifyTls
}
}
// NewApiService creates a instance of ApiService by passing ApiServiceOptions, then you can call methods.
func NewApiService(opts ...ApiServiceOption) *ApiService {
as := &ApiService{requester: &BasicRequester{}}
for _, opt := range opts {
opt(as)
}
if as.apiBaseURI == "" {
as.apiBaseURI = ProductionApiBaseURI
}
if as.apiKey != "" {
as.signer = NewKcSigner(as.apiKey, as.apiSecret, as.apiPassphrase)
}
return as
}
// NewApiServiceFromEnv creates a instance of ApiService by environmental variables such as `API_BASE_URI` `API_KEY` `API_SECRET` `API_PASSPHRASE`, then you can call the methods of ApiService.
func NewApiServiceFromEnv() *ApiService {
return NewApiService(
ApiBaseURIOption(os.Getenv("API_BASE_URI")),
ApiKeyOption(os.Getenv("API_KEY")),
ApiSecretOption(os.Getenv("API_SECRET")),
ApiPassPhraseOption(os.Getenv("API_PASSPHRASE")),
ApiSkipVerifyTlsOption(os.Getenv("API_SKIP_VERIFY_TLS") == "1"),
)
}
// Call calls the API by passing *Request and returns *ApiResponse.
func (as *ApiService) Call(request *Request) (*ApiResponse, error) {
defer func() {
if err := recover(); err != nil {
log.Println("[[Recovery] panic recovered:", err)
}
}()
request.BaseURI = as.apiBaseURI
request.SkipVerifyTls = as.apiSkipVerifyTls
request.Header.Set("Content-Type", "application/json")
request.Header.Set("User-Agent", "kumex-go-sdk/"+Version)
if as.signer != nil {
var b bytes.Buffer
b.WriteString(request.Method)
b.WriteString(request.RequestURI())
b.Write(request.Body)
h := as.signer.(*KcSigner).Headers(b.String())
for k, v := range h {
request.Header.Set(k, v)
}
}
rsp, err := as.requester.Request(request, request.Timeout)
if err != nil {
return nil, err
}
ar := &ApiResponse{response: rsp}
if err := rsp.ReadJsonBody(ar); err != nil {
rb, _ := rsp.ReadBody()
m := fmt.Sprintf("[Parse]Failure: parse JSON body failed because %s, %s %s with body=%s, respond code=%d body=%s",
err.Error(),
rsp.request.Method,
rsp.request.RequestURI(),
string(rsp.request.Body),
rsp.StatusCode,
string(rb),
)
return ar, errors.New(m)
}
return ar, nil
}