2022-10-22 18:01:55 +00:00
|
|
|
package server
|
|
|
|
|
|
|
|
import (
|
|
|
|
"log"
|
2022-11-19 10:41:10 +00:00
|
|
|
"net/http"
|
2022-10-22 18:01:55 +00:00
|
|
|
|
2022-11-19 10:41:10 +00:00
|
|
|
"github.com/gorilla/websocket"
|
2022-10-22 18:01:55 +00:00
|
|
|
)
|
|
|
|
|
2022-11-19 10:41:10 +00:00
|
|
|
var upgrader = websocket.Upgrader{} // use default options
|
2022-10-22 18:01:55 +00:00
|
|
|
|
2022-11-19 10:41:10 +00:00
|
|
|
func SocketHandler(w http.ResponseWriter, r *http.Request) {
|
|
|
|
conn, err := upgrader.Upgrade(w, r, nil)
|
2022-10-22 18:01:55 +00:00
|
|
|
if err != nil {
|
2022-11-19 10:41:10 +00:00
|
|
|
log.Print("Error during connection upgrading:", err)
|
|
|
|
return
|
2022-10-22 18:01:55 +00:00
|
|
|
}
|
2022-11-19 10:41:10 +00:00
|
|
|
defer conn.Close()
|
2022-10-22 18:01:55 +00:00
|
|
|
|
2022-11-19 10:41:10 +00:00
|
|
|
// The event loop
|
2022-10-22 18:01:55 +00:00
|
|
|
for {
|
2022-11-19 10:41:10 +00:00
|
|
|
messageType, message, err := conn.ReadMessage()
|
2022-10-22 18:01:55 +00:00
|
|
|
if err != nil {
|
2022-11-19 10:41:10 +00:00
|
|
|
log.Println("Error during message reading:", err)
|
|
|
|
break
|
2022-10-22 18:01:55 +00:00
|
|
|
}
|
2022-11-19 10:41:10 +00:00
|
|
|
log.Printf("Received: %s", message)
|
|
|
|
err = conn.WriteMessage(messageType, message)
|
|
|
|
if err != nil {
|
|
|
|
log.Println("Error during message writing:", err)
|
|
|
|
break
|
2022-10-22 18:01:55 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|