/
user.go
81 lines (70 loc) · 1.58 KB
/
user.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
package server
import (
"fmt"
"net/http"
"strings"
"time"
"github.com/MShoaei/trader/internal"
"github.com/adshao/go-binance/v2"
"github.com/gin-gonic/gin"
)
type User struct {
Client *binance.Client
Watchdogs map[ID]*internal.Watchdog
APIKey string
APISecret string
}
var allUsers = map[string]*User{}
func (s *Server) Register(c *gin.Context) {
data := struct {
Key string
Secret string
}{}
if err := c.BindJSON(&data); err != nil {
fail(c, http.StatusBadRequest, err)
return
}
if _, ok := allUsers[data.Key]; ok {
fail(c, http.StatusConflict, fmt.Errorf("API key already exists"))
return
}
allUsers[data.Key] = &User{
Watchdogs: make(map[ID]*internal.Watchdog, 100),
APIKey: data.Key,
APISecret: data.Secret,
}
}
type ID string
func NewWatchdogID(symbol string, interval string) ID {
return ID(symbol + "-" + interval)
}
func (id ID) GetSymbol() string {
return strings.Split(string(id), "-")[0]
}
func (id ID) GetInterval() string {
return strings.Split(string(id), "-")[1]
}
func (u *User) GetWatchdog(symbol string, interval string) (*internal.Watchdog, bool) {
id := NewWatchdogID(symbol, interval)
w, ok := u.Watchdogs[id]
return w, ok
}
func (u *User) DeleteWatchdog(symbol string, interval string) (bool, error) {
id := NewWatchdogID(symbol, interval)
w, ok := u.Watchdogs[id]
if !ok {
return false, nil
}
t := time.NewTimer(2 * time.Second)
select {
case w.StopC <- struct{}{}:
break
case <-t.C:
if !t.Stop() {
<-t.C
}
return false, fmt.Errorf("failed to stop the watchdog")
}
delete(u.Watchdogs, id)
return true, nil
}