Skip to content

Instantly share code, notes, and snippets.

@M0nteCarl0
Last active March 29, 2024 09:18
Show Gist options
  • Save M0nteCarl0/25376d48b984a680196ba40cdc3da0b2 to your computer and use it in GitHub Desktop.
Save M0nteCarl0/25376d48b984a680196ba40cdc3da0b2 to your computer and use it in GitHub Desktop.
Web socket notification receiver per user and backend server on golang
package main
import (
"log"
"net/http"
"time"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
)
type Message struct {
UserID string `json:"userId"`
Notification string `json:"notification"`
Timestamp time.Time `json:"timestamp"`
}
var (
upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
clients = make(map[string]*websocket.Conn)
)
func main() {
router := gin.Default()
router.GET("/ws", func(c *gin.Context) {
conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
log.Println("Failed to upgrade to WebSocket:", err)
return
}
userId := c.Query("userId")
clients[userId] = conn
log.Println("WebSocket connection established for user:", userId)
for {
// Read message from client
_, msg, err := conn.ReadMessage()
if err != nil {
log.Println("Failed to read message from WebSocket:", err)
delete(clients, userId)
break
}
log.Printf("Received message from user %s: %s\n", userId, msg)
}
})
router.GET("/send-notification", func(c *gin.Context) {
userId := c.Query("userId")
notification := c.Query("notification")
if conn, ok := clients[userId]; ok {
message := Message{
UserID: userId,
Notification: notification,
Timestamp: time.Now(),
}
err := conn.WriteJSON(message)
if err != nil {
log.Println("Failed to send notification to WebSocket:", err)
}
}
c.String(http.StatusOK, "Notification sent to user %s", userId)
})
log.Println("Backend server is running on port 8080")
router.Run(":8080")
}
let socket;
function connectWebSocket(userId) {
const url = `ws://localhost:8080/ws?userId=${userId}`;
socket = new WebSocket(url);
// Connection opened
socket.addEventListener('open', (event) => {
console.log('WebSocket connection established');
});
// Listen for messages
socket.addEventListener('message', (event) => {
const notification = JSON.parse(event.data);
console.log('Received notification:', notification);
// Do something with the notification data
});
// Connection closed
socket.addEventListener('close', (event) => {
console.log('WebSocket connection closed');
});
// Error occurred
socket.addEventListener('error', (event) => {
console.error('WebSocket error:', event);
});
}
function disconnectWebSocket() {
if (socket) {
socket.close();
socket = null;
console.log('WebSocket connection disconnected');
}
}
// Subscribe to notifications for a specific user
function subscribe(userId) {
if (!socket) {
connectWebSocket(userId);
} else {
console.log('WebSocket connection already established');
}
}
// Unsubscribe from notifications
function unsubscribe() {
disconnectWebSocket();
}
// Update WebSocket connection for a different user
function updateUser(userId) {
disconnectWebSocket();
connectWebSocket(userId);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment