-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
108 lines (91 loc) · 2.42 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"strings"
"github.com/gorilla/websocket"
gubrak "github.com/novalagung/gubrak/v2"
)
var connections = make([]*WebSocketConnection, 0)
const MESSAGE_NEW_USER = "New User"
const MESSAGE_CHAT = "Chat"
const MESSAGE_LEAVE = "Leave"
var upgrader = websocket.Upgrader{
ReadBufferSize: 0,
WriteBufferSize: 0, //1024
}
type SocketPayload struct {
Message string
}
type SocketResponse struct {
From string
Type string
Message string
}
type WebSocketConnection struct {
*websocket.Conn
Username string
}
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
content, err := ioutil.ReadFile("index.html")
if err != nil {
http.Error(w, "Dosya Açılamadı!", http.StatusInternalServerError)
}
fmt.Fprintf(w, "%s", content)
})
http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
gorillaConn, err := upgrader.Upgrade(w, r, w.Header())
if err != nil {
http.Error(w, "Websocket Bağlantısı Açılamadı", http.StatusInternalServerError)
}
user := r.URL.Query().Get("user")
currentConn := WebSocketConnection{Conn: gorillaConn, Username: user}
connections = append(connections, ¤tConn)
go handleIO(¤tConn, connections)
})
fmt.Println(":7000 working...")
http.ListenAndServe(":7000", nil)
}
func handleIO(currentConn *WebSocketConnection, connections []*WebSocketConnection) {
defer func() {
if r := recover(); r != nil {
log.Println("ERROR", fmt.Sprintf("%v", r))
}
}()
sendMessage(currentConn, MESSAGE_NEW_USER, "")
for {
payload := SocketPayload{}
err := currentConn.ReadJSON(&payload)
if err != nil {
if strings.Contains(err.Error(), "websocket: close") {
sendMessage(currentConn, MESSAGE_LEAVE, "")
ejectConnection(currentConn)
return
}
log.Println("ERROR", err.Error())
continue
}
sendMessage(currentConn, MESSAGE_CHAT, payload.Message)
}
}
func ejectConnection(currentConn *WebSocketConnection) {
filtered := gubrak.From(connections).Reject(func(each *WebSocketConnection) bool {
return each == currentConn
}).Result()
connections = filtered.([]*WebSocketConnection)
}
func sendMessage(currentConn *WebSocketConnection, kind, message string) {
for _, eachConn := range connections {
if eachConn == currentConn {
continue
}
eachConn.WriteJSON(SocketResponse{
From: currentConn.Username,
Type: kind,
Message: message,
})
}
}