Senior
How to organize internal notifications (bell on the website)? What transport to use?
sobes.tech AI
Answer from AI
To organize internal notifications with a bell on the website, WebSocket is often used — it is a bidirectional communication channel between the client and the server, allowing the server to send notifications in real-time without the need for constant polling.
Main steps:
- On the server (for example, in Go), implement a WebSocket server that maintains open connections with clients.
- On the client (in the browser), open a WebSocket connection and listen for events.
- When a new notification appears, the server sends a message via WebSocket to the specific user.
If WebSocket is not suitable (for example, due to infrastructural limitations), Server-Sent Events (SSE) can be used for one-way notifications or periodic polling with AJAX.
Example in Go using Gorilla WebSocket:
import (
"net/http"
"github.com/gorilla/websocket"
)
var upgrader = websocket.Upgrader{}
func wsHandler(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
return
}
defer conn.Close()
for {
// Wait for a message from the client or send notifications
_, _, err := conn.ReadMessage()
if err != nil {
break
}
// Here you can send notifications
err = conn.WriteMessage(websocket.TextMessage, []byte("New notification!"))
if err != nil {
break
}
}
}
func main() {
http.HandleFunc("/ws", wsHandler)
http.ListenAndServe(":8080", nil)
}
Thus, WebSocket is an optimal transport for internal notifications with a bell on the website.