-
Notifications
You must be signed in to change notification settings - Fork 0
/
conn.go
107 lines (92 loc) · 2.02 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 ws_for_micro
import (
"errors"
"io"
"log"
"sync"
"time"
"github.com/google/uuid"
"github.com/gorilla/websocket"
)
// Conn wraps websocket.Conn with Conn. It defines to listen and read
// data from Conn.
type Conn struct {
Conn *websocket.Conn
AfterReadFunc func(messageType int, r io.Reader)
BeforeCloseFunc func()
once sync.Once
id string
stopCh chan struct{}
}
// Write write p to the websocket connection. The error returned will always
// be nil if success.
func (c *Conn) Write(p []byte) (n int, err error) {
select {
case <-c.stopCh:
return 0, errors.New("Conn is closed, can't be written")
default:
err = c.Conn.WriteMessage(websocket.TextMessage, p)
if err != nil {
return 0, err
}
return len(p), nil
}
}
// GetID returns the id generated using UUID algorithm.
func (c *Conn) GetID() string {
c.once.Do(func() {
u := uuid.New()
c.id = u.String()
})
return c.id
}
// Listen listens for receive data from websocket connection. It blocks
// until websocket connection is closed.
func (c *Conn) Listen() {
c.Conn.SetCloseHandler(func(code int, text string) error {
if c.BeforeCloseFunc != nil {
c.BeforeCloseFunc()
}
if err := c.Close(); err != nil {
log.Println(err)
}
message := websocket.FormatCloseMessage(code, "")
c.Conn.WriteControl(websocket.CloseMessage, message, time.Now().Add(time.Second))
return nil
})
// Keeps reading from Conn util get error.
ReadLoop:
for {
select {
case <-c.stopCh:
break ReadLoop
default:
messageType, r, err := c.Conn.NextReader()
if err != nil {
// TODO: handle read error maybe
break ReadLoop
}
if c.AfterReadFunc != nil {
c.AfterReadFunc(messageType, r)
}
}
}
}
// Close close the connection.
func (c *Conn) Close() error {
select {
case <-c.stopCh:
return errors.New("Conn already been closed")
default:
c.Conn.Close()
close(c.stopCh)
return nil
}
}
// NewConn wraps conn.
func NewConn(conn *websocket.Conn) *Conn {
return &Conn{
Conn: conn,
stopCh: make(chan struct{}),
}
}