/
response.go
61 lines (51 loc) · 1.03 KB
/
response.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
package luxws
import (
"errors"
"sync"
)
// ErrIgnore is the error used by response handler callbacks when a given
// message needs to be ignored.
var ErrIgnore = errors.New("ignore response")
// ResponseHandlerFunc is the prototype for response handler callbacks.
type ResponseHandlerFunc func([]byte) error
type responseHandler struct {
mu sync.Mutex
done chan struct{}
err error
fn ResponseHandlerFunc
}
func newResponseHandler(fn ResponseHandlerFunc) *responseHandler {
return &responseHandler{
done: make(chan struct{}),
fn: fn,
}
}
func (h *responseHandler) Done() <-chan struct{} {
h.mu.Lock()
d := h.done
h.mu.Unlock()
return d
}
func (h *responseHandler) Err() error {
h.mu.Lock()
err := h.err
h.mu.Unlock()
return err
}
func (h *responseHandler) Handle(payload []byte) {
h.mu.Lock()
select {
case <-h.done:
h.mu.Unlock()
return
default:
}
fn := h.fn
h.mu.Unlock()
if err := fn(payload); err == nil || !errors.Is(err, ErrIgnore) {
h.mu.Lock()
h.err = err
close(h.done)
h.mu.Unlock()
}
}