-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.go
217 lines (187 loc) · 5.03 KB
/
server.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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
// (c) MASSIVE ART WebServices GmbH
//
// This source file is subject to the MIT license that is bundled
// with this source code in the file LICENSE.
package engineio
import (
"encoding/json"
"errors"
"io"
"net/http"
"strconv"
"time"
)
var (
ErrUnknownSession = errors.New("unknown session id")
ErrQueueFull = errors.New("queue limit reached")
ErrNotConnected = errors.New("not connected")
)
// EngineIO handles transport abstraction and provide the user a handfull
// of callbacks to observe different events.
type EngineIO struct {
sessions map[string]Connection
remove chan string
config *Config
connectionFunc func(Connection)
messageFunc func(Connection, []byte) error
closeFunc func(Connection)
}
// NewEngineIO allocates and returns a new EngineIO. If config is nil,
// the DefaultConfig is used.
func NewEngineIO(config *Config) *EngineIO {
e := &EngineIO{
sessions: make(map[string]Connection),
remove: make(chan string),
}
if config == nil {
e.config = DefaultConfig
} else {
e.config = config
}
go e.remover()
return e
}
// Close closes the engineio server and all it's connections.
func (e EngineIO) Close() error {
for _, conn := range e.sessions {
conn.Close()
}
close(e.remove)
return nil
}
func (e EngineIO) remover() {
for {
sid := <-e.remove
delete(e.sessions, sid)
}
}
// handshake returns a polling connection and an error if any.
// TODO: implement websocket handshake
func (e *EngineIO) handshake(w io.Writer, sid string, index int) (Connection, error) {
var payload = struct {
Sid string `json:"sid"`
Upgrades []string `json:"upgrades"`
PingInterval int64 `json:"pingInterval"`
PingTimeout int64 `json:"pingTimeout"`
}{
Sid: sid,
PingInterval: e.config.PingInterval,
PingTimeout: e.config.PingTimeout,
Upgrades: e.config.Upgrades,
}
data, err := json.Marshal(payload)
if err != nil {
return nil, err
}
// TODO
conn := &pollingConn{
queue: make(chan packet, e.config.QueueLength+maxHeartbeat),
connections: make(map[int64]*pollingWriter),
connected: true,
index: index,
sid: sid,
remove: e.remove,
pingInterval: time.Duration(e.config.PingInterval),
queueLength: e.config.QueueLength + maxHeartbeat,
}
// polling queue flusher
go conn.flusher()
_, err = w.Write(conn.encode(packet{
index: index,
Type: openID,
Data: data,
}))
if err != nil {
return nil, err
}
return conn, nil
}
type AuthFunc func(*http.Request) bool
func (e *EngineIO) Handler(w http.ResponseWriter, req *http.Request, fn AuthFunc) {
var err error
sid := req.FormValue("sid")
jindex := req.FormValue("j")
index := -1
if jindex != "" {
index, err = strconv.Atoi(jindex)
if err != nil {
http.Error(w, "atoi: "+err.Error(), http.StatusBadRequest)
return
}
}
switch uint(len(sid)) {
case 0:
sid = newSessionId()
if fn != nil {
if !fn(req) {
http.Error(w, "not authorized", http.StatusUnauthorized)
return
}
}
conn, err := e.handshake(w, sid, index)
if err != nil {
http.Error(w, "handshake: "+err.Error(), http.StatusInternalServerError)
return
}
// initialize function callbacks
if e.connectionFunc != nil {
e.connectionFunc(conn)
}
conn.messageFunc(e.messageFunc)
conn.closeFunc(e.closeFunc)
e.sessions[sid] = conn
default:
conn, found := e.sessions[sid]
if !found {
http.Error(w, ErrUnknownSession.Error(), http.StatusBadRequest)
return
}
if upgrade := req.Header.Get("Upgrade"); upgrade == "websocket" {
prevConn := conn
newConn := &websocketConn{
prevConn: prevConn,
sid: sid,
remove: e.remove,
pingTimeout: time.Duration(e.config.PingTimeout),
}
// initialize function callbacks
newConn.closeFunc(e.closeFunc)
newConn.messageFunc(e.messageFunc)
if err := newConn.handle(w, req); err != nil {
// got i/o timeout, remove session; we can't send
// andy error message on a hijack'd connection.
select {
case e.remove <- sid:
default:
}
return
}
return
}
// polling connection
conn.(*pollingConn).index = index
if err := conn.handle(w, req); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
}
// ConnectionFunc sets fn to be invoked when a new connection is
// established. It passes the established connection as an argument to
// the callback.
func (e *EngineIO) ConnectionFunc(fn func(Connection)) {
e.connectionFunc = fn
}
// MessageFunc sets fn to be invoked when a message arrives. It passes
// the established connection along with the received message datai as
// arguments to the callback.
func (e *EngineIO) MessageFunc(fn func(Connection, []byte) error) {
e.messageFunc = fn
}
// CloseFunc sets fn to be invoked when a session is considered to be
// lost. It passes the established connection as an argument to the
// callback. After disconnection the connection is considered to be
// destroyed, and it should not be used anymore.
func (e *EngineIO) CloseFunc(fn func(Connection)) {
e.closeFunc = fn
}