-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathconn.go
107 lines (84 loc) · 1.79 KB
/
conn.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
package jsonrpc2
import (
"sync"
"net/http"
)
type notifyEvent struct {
method string
params interface{}
}
// ConnCloseHandler ...
type ConnCloseHandler func()
// Conn ...
type Conn struct {
Request *http.Request
rwc *ReadWriteCloser
codec ServerCodec
sending *sync.Mutex
closed bool
mu sync.RWMutex
closeHandlers []ConnCloseHandler
extraData map[string]interface{}
}
// NewConn ...
func NewConn(req *http.Request, sending *sync.Mutex, codec ServerCodec) *Conn {
conn := &Conn{
Request: req,
sending: sending,
codec: codec,
extraData: make(map[string]interface{}),
}
return conn
}
func (c *Conn) ternimating() {
c.mu.Lock()
defer c.mu.Unlock()
c.closed = true
for _, handler := range c.closeHandlers {
handler()
}
c.closeHandlers = []ConnCloseHandler{}
}
// Notify ...
func (c *Conn) Notify(method string, params interface{}) error {
c.sending.Lock()
defer c.sending.Unlock()
return c.codec.WriteNotification(method, params)
}
// NotifyEx ...
func (c *Conn) NotifyEx(method string, params interface{}) error {
c.sending.Lock()
defer c.sending.Unlock()
return c.codec.WriteNotificationEx(method, params)
}
// Close ...
func (c *Conn) Close() error {
return c.codec.Close()
}
// OnClose ...
func (c *Conn) OnClose(f ConnCloseHandler) {
c.mu.Lock()
defer c.mu.Unlock()
if c.closed {
go f()
}
c.closeHandlers = append(c.closeHandlers, f)
}
// GetData ...
func (c *Conn) GetData(key string) interface{} {
c.mu.RLock()
defer c.mu.RUnlock()
return c.extraData[key]
}
// SetData ...
func (c *Conn) SetData(key string, value interface{}) {
c.mu.Lock()
defer c.mu.Unlock()
c.extraData[key] = value
}
// DelData ...
func (c *Conn) DelData(key string) {
c.mu.Lock()
defer c.mu.Unlock()
delete(c.extraData, key)
}