Skip to content

Instantly share code, notes, and snippets.

@M0nteCarl0
Created July 28, 2023 07:12
Show Gist options
  • Save M0nteCarl0/2ab52c0830d8a47174a2321a6f167c9a to your computer and use it in GitHub Desktop.
Save M0nteCarl0/2ab52c0830d8a47174a2321a6f167c9a to your computer and use it in GitHub Desktop.
Web socket notification on golang
<!DOCTYPE html>
<html>
<head>
<title>Notifications</title>
<script>
var socket = new WebSocket("ws://" + window.location.host + "/ws");
socket.onmessage = function(event) {
var notification = JSON.parse(event.data);
alert("Title: " + notification.title + "\nMessage: " + notification.message);
};
function sendNotification() {
var title = document.getElementById("title").value;
var message = document.getElementById("message").value;
var notification = {
title: title,
message: message
};
socket.send(JSON.stringify(notification));
}
</script>
</head>
<body>
<h1>Notifications</h1>
<form>
<label for="title">Title:</label>
<input type="text" id="title" required><br><br>
<label for="message">Message:</label>
<textarea id
package main
import (
"log"
"net/http"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
)
var clients = make(map[*websocket.Conn]bool)
var broadcast = make(chan Notification)
type Notification struct {
Title string `json:"title"`
Message string `json:"message"`
}
var upgrader = websocket.Upgrader{}
func main() {
r := gin.Default()
r.LoadHTMLGlob("templates/*")
// Обработчик GET-запроса для отображения страницы с подключением к веб-сокетам
r.GET("/notifications", func(c *gin.Context) {
c.HTML(http.StatusOK, "notifications.html", nil)
})
// Обработчик WebSocket-подключения
r.GET("/ws", func(c *gin.Context) {
conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
log.Println(err)
return
}
defer conn.Close()
clients[conn] = true
for {
var notification Notification
err := conn.ReadJSON(&notification)
if err != nil {
log.Println(err)
delete(clients, conn)
break
}
broadcast <- notification
}
})
// Функция для отправки уведомлений всем подключенным клиентам
go func() {
for {
notification := <-broadcast
for client := range clients {
err := client.WriteJSON(notification)
if err != nil {
log.Println(err)
client.Close()
delete(clients, client)
}
}
}
}()
r.Run(":8080")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment