/
websocket.go
49 lines (41 loc) · 1.19 KB
/
websocket.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
package v1
import (
"encoding/json"
"net/http"
"github.com/freeusd/solebtc/Godeps/_workspace/src/github.com/gin-gonic/gin"
"github.com/freeusd/solebtc/Godeps/_workspace/src/github.com/gorilla/websocket"
"github.com/freeusd/solebtc/models"
)
var defaultUpgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool { return true }, // allow any origin to connect
}
// Websocket entry
func Websocket(
getUsersOnline dependencyGetUsersOnline,
getConfig dependencyGetSystemConfig,
getLatestIncomes dependencyGetLatestIncomes,
broadcast dependencyBroadcast,
putConn dependencyPutConn,
) gin.HandlerFunc {
return func(c *gin.Context) {
// upgrade http conn to ws conn
conn, err := defaultUpgrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
return
}
// increment usersOnline by 1
usersOnline := getUsersOnline() + 1
// send msg to client
conn.WriteJSON(models.WebsocketMessage{
UsersOnline: usersOnline,
LatestIncomes: getLatestIncomes(),
})
// broadcast users_online to all other clients
broadcastMsg, _ := json.Marshal(models.WebsocketMessage{
UsersOnline: usersOnline,
})
broadcast(broadcastMsg)
// put connection in hub
putConn(conn)
}
}