Files
antrean-anjungan/docs/websocket.md
2025-09-18 19:01:22 +07:00

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_id and room query 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 useWebSocket to manage connection, messages, and sending.
  • UI allows sending messages and displays received messages.

Running the Nuxt 3 Client

  1. Navigate to the client directory:
cd examples/nuxt3-websocket-client
  1. Install dependencies:
npm install
  1. Run the development server:
npm run dev
  1. Open the browser at http://localhost:3000 (or the port shown in the terminal).

  2. 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_URL or defaults to ws://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.