-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathmain.go
79 lines (52 loc) · 1.28 KB
/
main.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
package main
import (
"net/http"
"fmt"
"github.com/gorilla/websocket"
"log"
"github.com/satori/go.uuid"
"pubsub/pubsub"
)
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
func autoId() (string) {
return uuid.Must(uuid.NewV4()).String()
}
var ps = &pubsub.PubSub{}
func websocketHandler(w http.ResponseWriter, r *http.Request) {
upgrader.CheckOrigin = func(r *http.Request) bool {
return true
}
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Println(err)
return
}
client := pubsub.Client{
Id: autoId(),
Connection: conn,
}
// add this client into the list
ps.AddClient(client)
fmt.Println("New Client is connected, total: ", len(ps.Clients))
for {
messageType, p, err := conn.ReadMessage()
if err != nil {
log.Println("Something went wrong", err)
ps.RemoveClient(client)
log.Println("total clients and subscriptions ", len(ps.Clients), len(ps.Subscriptions))
return
}
ps.HandleReceiveMessage(client, messageType, p)
}
}
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "static")
})
http.HandleFunc("/ws", websocketHandler)
http.ListenAndServe(":3000", nil)
fmt.Println("Server is running: http://localhost:3000")
}