add WebSocket support for real-time delivery updates with JWT authentication and automatic reconnection
Some checks failed
Build and Push Docker Images / build-backend (push) Has been cancelled
Build and Push Docker Images / build-frontend (push) Has been cancelled

This commit is contained in:
Egor Pozharov
2026-05-21 15:52:05 +06:00
parent c87aea47ce
commit d1efebbb34
16 changed files with 408 additions and 73 deletions

View File

@@ -0,0 +1,41 @@
package ws
import (
"net/http"
"github.com/chedius/delivery-tracker/internal/auth"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
)
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool { return true },
}
// HandleWS returns a Gin handler that upgrades HTTP to WebSocket
// after validating the JWT token from the ?token= query param.
func HandleWS(hub *Hub, jwtSecret []byte) gin.HandlerFunc {
return func(c *gin.Context) {
token := c.Query("token")
if token == "" {
c.JSON(http.StatusUnauthorized, gin.H{"error": "missing token"})
return
}
if _, err := auth.ParseToken(token, jwtSecret); err != nil {
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid token"})
return
}
conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
return
}
client := NewClient(hub, conn)
hub.Register(client)
go client.WritePump()
go client.ReadPump()
}
}