/
send_handler.go
84 lines (72 loc) · 1.62 KB
/
send_handler.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
package main
import (
"github.com/Cretezy/dSock/common"
"github.com/Cretezy/dSock/common/protos"
"github.com/gin-gonic/gin"
"io/ioutil"
)
func sendHandler(c *gin.Context) {
connId := c.Query("id")
user := c.Query("user")
session := c.Query("session")
// Get all worker IDs that the target is connected to
workerIds, apiError := resolveWorkers(common.ResolveOptions{
Connection: connId,
User: user,
Session: session,
})
if apiError != nil {
apiError.Send(c)
return
}
parsedMessageType := ParseMessageType(c.Query("type"))
if parsedMessageType == -1 {
apiError := common.ApiError{
StatusCode: 400,
ErrorCode: common.ErrorInvalidMessageType,
}
apiError.Send(c)
return
}
// Read full body (message data)
body, err := ioutil.ReadAll(c.Request.Body)
if err != nil {
apiError := common.ApiError{
StatusCode: 500,
ErrorCode: common.ErrorReadingMessage,
}
apiError.Send(c)
return
}
// Prepare message for worker
message := &protos.Message{
Body: body,
User: user,
Connection: connId,
Session: c.Query("session"),
Type: parsedMessageType,
}
// Send to all workers
apiError = sendToWorkers(workerIds, message)
if apiError != nil {
apiError.Send(c)
return
}
c.AbortWithStatusJSON(200, map[string]interface{}{
"success": true,
})
}
/// Parse message type, allowing for WebSocket frame type ID
func ParseMessageType(messageType string) protos.Message_MessageType {
switch messageType {
case "text":
fallthrough
case "1":
return protos.Message_TEXT
case "binary":
fallthrough
case "2":
return protos.Message_BINARY
}
return -1
}