/
streaming.go
148 lines (131 loc) · 3.1 KB
/
streaming.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
package zaif
import (
"context"
"errors"
"sync"
"github.com/gorilla/websocket"
"golang.org/x/sync/errgroup"
)
// StreamResponse stream API response
type StreamResponse struct {
Asks [][]float64 `json:"asks"`
Bids [][]float64 `json:"bids"`
TargetUsers []string `json:"target_users"`
Trades []struct {
CurrentyPair string `json:"currenty_pair"`
TradeType string `json:"trade_type"`
Price float64 `json:"price"`
CurrencyPair string `json:"currency_pair"`
Tid int64 `json:"tid"`
Amount float64 `json:"amount"`
Date int `json:"date"`
} `json:"trades"`
LastPrice struct {
Action string `json:"action"`
Price float64 `json:"price"`
} `json:"last_price"`
CurrencyPair string `json:"currency_pair"`
Timestamp string `json:"timestamp"`
}
// NewStream stream API用のクライアントを作る
func NewStream() Stream {
return Stream{
subscriptions: make(map[string]chan *StreamResponse),
connections: make(map[string]*websocket.Conn),
}
}
// Stream client
type Stream struct {
subscriptions map[string]chan *StreamResponse
connections map[string]*websocket.Conn
connected bool
mu sync.Mutex
Error error
}
// AddSubscription 指定ペアのsubscribe
// resはClose()が呼ばれた時にcloseされます
func (s *Stream) AddSubscription(pair string, res chan *StreamResponse) error {
s.mu.Lock()
defer s.mu.Unlock()
s.subscriptions[pair] = res
return nil
}
// Receive stream APIからデータを受信開始する
func (s *Stream) Receive(ctx context.Context) error {
// Make connections
s.mu.Lock()
if s.connected {
return errors.New("already started")
}
s.connected = true
for k := range s.subscriptions {
conn, _, err := websocket.DefaultDialer.Dial("wss://ws.zaif.jp:8888/stream?currency_pair="+k, nil)
if err != nil {
for _, conn := range s.connections {
conn.Close()
}
for _, sub := range s.subscriptions {
close(sub)
}
s.mu.Unlock()
return err
}
s.connections[k] = conn
}
// Receiving responses
wg, ctx := errgroup.WithContext(ctx)
for pair, conn := range s.connections {
conn := conn
c := s.subscriptions[pair]
wg.Go(func() error {
for {
// if context already done, finish
if ctx.Err() != nil {
return nil
}
// Wait data...
var res StreamResponse
if err := conn.ReadJSON(&res); err != nil {
// this is not an error actually
if ctx.Err() != nil {
return nil
}
return err
}
// Publish to subscribers
s.mu.Lock()
if s.connected {
c <- &res
}
s.mu.Unlock()
}
})
}
// Wait context to done
// cleanup connections
wg.Go(func() error {
<-ctx.Done()
s.mu.Lock()
defer s.mu.Unlock()
for _, sb := range s.connections {
sb.Close()
}
s.connections = map[string]*websocket.Conn{}
return nil
})
s.mu.Unlock()
return wg.Wait()
}
// Close connections
func (s *Stream) Close() error {
var err error
s.mu.Lock()
defer s.mu.Unlock()
for k, c := range s.subscriptions {
close(c)
s.subscriptions[k] = nil
s.connections[k] = nil
}
s.connected = false
return err
}