2.4 KiB
2.4 KiB
WebSocket Server and Nuxt 3 Client Documentation
Overview
This document describes the WebSocket server implementation in the Go API service and how to use the Nuxt 3 client example to connect and interact with the WebSocket server.
WebSocket Server
- Implemented using Gorilla WebSocket and Gin framework.
- Located at
internal/handlers/websocket/websocket.go. - WebSocket endpoint is registered at
/api/v1/ws. - Supports client connections with optional
user_idandroomquery parameters. - Supports broadcasting messages to all clients, specific rooms, or individual clients.
- Includes heartbeat and simulated data stream features for demonstration.
Server Usage
- Connect to the WebSocket endpoint:
ws://<server-address>/api/v1/ws?user_id=<user>&room=<room> - Messages are JSON objects with the following structure:
{
"type": "message_type",
"data": { ... },
"timestamp": "ISO8601 timestamp",
"client_id": "optional client id"
}
- The server broadcasts messages to all clients or specific rooms based on message type and data.
Nuxt 3 WebSocket Client Example
- Located in
examples/nuxt3-websocket-client/. - Connects to the WebSocket server using the URL configured in
nuxt.config.ts(public.websocketUrl). - Uses a Vue composable
useWebSocketto manage connection, messages, and sending. - UI allows sending messages and displays received messages.
Running the Nuxt 3 Client
- Navigate to the client directory:
cd examples/nuxt3-websocket-client
- Install dependencies:
npm install
- Run the development server:
npm run dev
-
Open the browser at
http://localhost:3000(or the port shown in the terminal). -
The client will connect to the WebSocket server and display connection status and messages.
Configuration
- The WebSocket URL can be configured via environment variable
WEBSOCKET_URLor defaults tows://localhost:8080/api/v1/ws.
Notes
- Ensure the Go API server is running and accessible at the configured WebSocket URL.
- The WebSocket server allows cross-origin connections for development; adjust origin checks for production.
- The client example uses Tailwind CSS for styling.
Summary
This setup provides a full WebSocket server in Go with a modern Nuxt 3 client example demonstrating real-time communication. Use this as a foundation for building real-time features in your applications.