-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.go
88 lines (71 loc) · 1.67 KB
/
index.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
package main
import (
"fmt"
"net/http"
"github.com/gorilla/websocket"
)
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
},
}
var clients = make(map[*websocket.Conn]bool)
var broadcast = make(chan Message)
type Message struct {
Username string `json:"username"`
Date string `json:"date"`
Message string `json:"message"`
}
func main() {
port := ":8080"
http.HandleFunc("/", handleConnections)
go handleMessages()
fmt.Printf("Server started on %s", port)
err := http.ListenAndServe(port, nil)
if err != nil {
panic("Error starting server: " + err.Error())
}
}
func handleConnections(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
fmt.Println(err)
return
}
defer conn.Close()
clients[conn] = true
fmt.Printf("\nActive connections: %d", activeConnections())
for {
var msg Message
err := conn.ReadJSON(&msg)
if err != nil {
fmt.Println(err)
delete(clients, conn)
return
}
broadcast <- msg
}
}
func handleMessages() {
for {
msg := <-broadcast
for client := range clients {
err := client.WriteJSON(msg)
if err != nil {
fmt.Println(err)
client.Close()
delete(clients, client)
}
}
}
}
// ikke nødvendig, men morro å se tenker jeg :p
func activeConnections() int {
count := 0
for _, isConnected := range clients {
if isConnected {
count++
}
}
return count
}