forked from davidfowl/signalr-ports
-
Notifications
You must be signed in to change notification settings - Fork 0
/
websocketServer.go
59 lines (53 loc) · 1.67 KB
/
websocketServer.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
package signalr
import (
"crypto/rand"
"encoding/base64"
"encoding/json"
"fmt"
"golang.org/x/net/websocket"
"net/http"
)
// MapHub used to register a SignalR Hub with the specified ServeMux
func MapHub(mux *http.ServeMux, path string, hubProto HubInterface) *Server {
mux.HandleFunc(fmt.Sprintf("%s/negotiateWebSocketTestServer", path), negotiateHandler)
server, _ := NewServer(SimpleHubFactory(hubProto))
mux.Handle(path, websocket.Handler(func(ws *websocket.Conn) {
connectionID := ws.Request().URL.Query().Get("id")
if len(connectionID) == 0 {
// Support websocket connection without negotiateWebSocketTestServer
connectionID = getConnectionID()
}
server.Run(&webSocketConnection{ws, connectionID})
}))
return server
}
func negotiateHandler(w http.ResponseWriter, req *http.Request) {
if req.Method != "POST" {
w.WriteHeader(400)
} else {
response := negotiateResponse{
ConnectionID: getConnectionID(),
AvailableTransports: []availableTransport{
{
Transport: "WebSockets",
TransferFormats: []string{"Text", "Binary"},
},
},
}
_ = json.NewEncoder(w).Encode(response) // Can't imagine an error when encoding
}
}
func getConnectionID() string {
bytes := make([]byte, 16)
// rand.Read only fails when the systems random number generator fails. Rare case, ignore
_, _ = rand.Read(bytes)
return base64.StdEncoding.EncodeToString(bytes)
}
type availableTransport struct {
Transport string `json:"transport"`
TransferFormats []string `json:"transferFormats"`
}
type negotiateResponse struct {
ConnectionID string `json:"connectionId"`
AvailableTransports []availableTransport `json:"availableTransports"`
}