-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.go
113 lines (96 loc) · 2.61 KB
/
app.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
package main
import (
"context"
"fmt"
"strconv"
"sync"
"crypto-monitor/backend"
"github.com/iaping/go-okx/ws/public"
"github.com/wailsapp/wails/v2/pkg/runtime"
)
// App struct
type App struct {
ctx context.Context
subscribedPairs map[string]bool
mu sync.Mutex
}
// NewApp creates a new App application struct
func NewApp() *App {
return &App{
subscribedPairs: make(map[string]bool),
}
}
// startup is called when the app starts. The context is saved
// so we can call the runtime methods
func (a *App) startup(ctx context.Context) {
a.ctx = ctx
runtime.EventsOn(ctx, "crypto_pairs_changed", a.handleCryptoPairsChanged)
}
// handleCryptoPairsChanged 是包装后的事件处理函数
func (a *App) handleCryptoPairsChanged(data ...interface{}) {
if len(data) < 1 {
fmt.Println("did not receive any data")
return
}
pairsInterface, ok := data[0].([]interface{})
if !ok {
fmt.Println("received data format is incorrect")
return
}
pairs := make([]string, 0, len(pairsInterface))
for _, pair := range pairsInterface {
if p, ok := pair.(string); ok {
pairs = append(pairs, p)
} else {
fmt.Println("pair is not a string")
}
}
a.subscribeCryptoPrices(pairs)
}
// subscribeCryptoPrices subscribes to the prices of the given crypto pairs
func (a *App) subscribeCryptoPrices(pairs []string) {
a.mu.Lock()
defer a.mu.Unlock()
for _, pair := range pairs {
if a.subscribedPairs[pair] {
continue
}
tickerChan, err := backend.GetCryptoPairListener(pair)
if err != nil {
priceInfo := map[string]interface{}{
"pair": pair,
"error": err.Error(),
}
runtime.EventsEmit(a.ctx, "ticker_subscription_error", priceInfo)
continue
}
a.subscribedPairs[pair] = true
go func(pair string, ch <-chan public.EventTickers) {
for ticker := range ch {
last, _ := strconv.ParseFloat(ticker.Data[0].Last, 64)
sodUtc0, _ := strconv.ParseFloat(ticker.Data[0].SodUtc0, 64)
percentage := (last - sodUtc0) / sodUtc0 * 100
percentageStr := ""
if percentage > 0 {
percentageStr = fmt.Sprintf("+%.2f%%", percentage)
} else {
percentageStr = fmt.Sprintf("%.2f%%", percentage)
}
priceInfo := map[string]interface{}{
"pair": pair,
"price": ticker.Data[0].Last,
"percentage": percentageStr,
}
runtime.EventsEmit(a.ctx, "ticker_update", priceInfo)
}
a.mu.Lock()
delete(a.subscribedPairs, pair)
a.mu.Unlock()
priceInfo := map[string]interface{}{
"pair": pair,
"msg": "ticker subscription closed",
}
runtime.EventsEmit(a.ctx, "ticker_subscription_closed", priceInfo)
}(pair, tickerChan)
}
}