forked from googollee/go-socket.io
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
209 lines (181 loc) · 4.84 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
package socketio
import (
"code.google.com/p/go.net/websocket"
"fmt"
"net/http"
"regexp"
"strings"
"sync"
)
var (
uriRegexp = regexp.MustCompile(`^(.+?)/(1)(?:/([^/]+)/([^/]+))?/?$`)
)
type Config struct {
HeartbeatTimeout int
ClosingTimeout int
NewSessionID func() string
Transports *TransportManager
Authorize func(*http.Request, map[interface{}]interface{}) bool
}
type SocketIOServer struct {
*http.ServeMux
mutex sync.RWMutex
heartbeatTimeout int
closingTimeout int
authorize func(*http.Request, map[interface{}]interface{}) bool
newSessionId func() string
transports *TransportManager
sessions map[string]*Session
eventEmitters map[string]*EventEmitter
}
func NewSocketIOServer(config *Config) *SocketIOServer {
server := &SocketIOServer{ServeMux: http.NewServeMux()}
if config != nil {
server.heartbeatTimeout = config.HeartbeatTimeout
server.closingTimeout = config.ClosingTimeout
server.newSessionId = config.NewSessionID
server.transports = config.Transports
server.authorize = config.Authorize
}
if server.heartbeatTimeout == 0 {
server.heartbeatTimeout = 15000
}
if server.closingTimeout == 0 {
server.closingTimeout = 10000
}
if server.newSessionId == nil {
server.newSessionId = NewSessionID
}
if server.transports == nil {
server.transports = DefaultTransports
}
server.sessions = make(map[string]*Session)
server.eventEmitters = make(map[string]*EventEmitter)
return server
}
func (srv *SocketIOServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
path := r.URL.Path
if !strings.HasPrefix(path, "/socket.io/1/") {
cookie, _ := r.Cookie("socket.io.sid")
if cookie == nil {
http.SetCookie(w, &http.Cookie{
Name: "socket.io.sid",
Value: NewSessionID(),
Path: "/",
})
}
srv.ServeMux.ServeHTTP(w, r)
return
}
path = path[len("/socket.io/1/"):]
if path == "" {
srv.handShake(w, r)
return
}
spliter := strings.SplitN(path, "/", 2)
if len(spliter) < 2 {
http.NotFound(w, r)
return
}
transportName, sessionId := spliter[0], spliter[1]
if transportName != "websocket" {
http.Error(w, "not websocket", http.StatusBadRequest)
return
}
session := srv.getSession(sessionId)
if session == nil {
http.Error(w, "invalid session id", http.StatusBadRequest)
return
}
// open
transport := newWebSocket(session)
websocket.Handler(transport.webSocketHandler).ServeHTTP(w, r)
}
func (srv *SocketIOServer) Of(name string) *EventEmitter {
ret, ok := srv.eventEmitters[name]
if !ok {
ret = NewEventEmitter()
srv.eventEmitters[name] = ret
}
return ret
}
func (srv *SocketIOServer) In(name string) *Broadcaster {
namespaces := []*NameSpace{}
for _, session := range srv.sessions {
ns := session.Of(name)
if ns != nil {
namespaces = append(namespaces, ns)
}
}
return &Broadcaster{Namespaces: namespaces}
}
func (srv *SocketIOServer) Broadcast(name string, args ...interface{}) {
srv.In("").Broadcast(name, args...)
}
func (srv *SocketIOServer) Except(ns *NameSpace) *Broadcaster {
return srv.In("").Except(ns)
}
func (srv *SocketIOServer) On(name string, fn interface{}) error {
return srv.Of("").On(name, fn)
}
func (srv *SocketIOServer) RemoveListener(name string, fn interface{}) {
srv.Of("").RemoveListener(name, fn)
}
func (srv *SocketIOServer) RemoveAllListeners(name string) {
srv.Of("").RemoveAllListeners(name)
}
// authorize origin!!
func (srv *SocketIOServer) handShake(w http.ResponseWriter, r *http.Request) {
var values = make(map[interface{}]interface{})
if srv.authorize != nil {
if ok := srv.authorize(r, values); !ok {
http.Error(w, "", 401)
return
}
}
w.Header().Set("Access-Control-Allow-Origin", r.Header.Get("origin"))
w.Header().Set("Access-Control-Allow-Methods", "GET")
w.Header().Set("Access-Control-Allow-Credentials", "true")
cookie, _ := r.Cookie("socket.io.sid")
var sessionId string
if cookie == nil {
sessionId = NewSessionID()
} else {
sessionId = cookie.Value
}
if sessionId == "" {
http.Error(w, "", 503)
return
}
transportNames := srv.transports.GetTransportNames()
fmt.Fprintf(w, "%s:%d:%d:%s",
sessionId,
srv.heartbeatTimeout,
srv.closingTimeout,
strings.Join(transportNames, ","))
session := srv.getSession(sessionId)
if session == nil {
session = NewSession(srv.eventEmitters, sessionId, srv.heartbeatTimeout, true, r)
srv.addSession(session)
}
if values != nil {
for k, v := range values {
session.Values[k] = v
}
}
}
func (srv *SocketIOServer) addSession(ss *Session) {
srv.mutex.Lock()
defer srv.mutex.Unlock()
srv.sessions[ss.SessionId] = ss
}
func (srv *SocketIOServer) removeSession(ss *Session) {
srv.mutex.Lock()
defer srv.mutex.Unlock()
delete(srv.sessions, ss.SessionId)
}
func (srv *SocketIOServer) getSession(sessionId string) *Session {
srv.mutex.RLock()
defer srv.mutex.RUnlock()
return srv.sessions[sessionId]
}