# ๐Ÿš€ WebSocket API Service - Real-Time Communication > **Modern WebSocket API service with advanced real-time communication, client management, and broadcasting capabilities** ## ๐Ÿ“‘ Daftar Isi - [โœจ Fitur Utama](#-fitur-utama) - [๐Ÿ—๏ธ Arsitektur](#%EF%B8%8F-arsitektur) - [โšก Quick Start](#-quick-start) - [๐Ÿ” Autentikasi](#-autentikasi) - [๐Ÿ“Š API Endpoints](#-api-endpoints) - [๐Ÿ› ๏ธ Development](#%EF%B8%8F-development) - [๐Ÿš€ Deployment](#-deployment) - [๐Ÿ“š Dokumentasi](#-dokumentasi) *** ## โœจ Fitur Utama ### Real-Time Communication - **๐Ÿ”„ WebSocket Server** - High-performance WebSocket server dengan auto-reconnect - **๐Ÿ  Room Management** - Multi-room support untuk isolated communication - **๐Ÿ‘ฅ Client Tracking** - Advanced client identification (IP-based, static ID, generated) - **๐Ÿ“ก Real-time Broadcasting** - Server-initiated broadcasts ke semua atau specific clients - **๐Ÿ’ฌ Direct Messaging** - Peer-to-peer messaging antar clients - **๐Ÿ”„ Database Notifications** - PostgreSQL LISTEN/NOTIFY integration ### Advanced Features - **๐Ÿ“Š Connection Monitoring** - Real-time statistics dan health monitoring - **๐Ÿงน Auto Cleanup** - Automatic cleanup untuk inactive connections - **๐Ÿ”’ Secure Authentication** - JWT-based authentication untuk WebSocket connections - **๐Ÿ“ˆ Performance Metrics** - Built-in performance tracking dan analytics - **๐ŸŽฏ Message Queue** - High-throughput message processing dengan worker pools - **๐Ÿ” Activity Logging** - Comprehensive activity logging untuk debugging ### Developer Experience - **๐Ÿ”ฅ Hot Reload** - Development dengan auto-restart - **๐Ÿณ Docker Ready** - Easy deployment dengan Docker - **โšก Code Generator** - Buat handler dan model otomatis - **๐Ÿงช Testing Suite** - Unit dan integration tests - **๐Ÿ“Š Health Monitoring** - Monitoring kesehatan aplikasi *** ## ๐Ÿ—๏ธ Arsitektur WebSocket ### WebSocket Architecture Layers ``` โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚ WebSocket Layer โ”‚ โ† websocket.go, broadcast.go โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค โ”‚ Application Layer โ”‚ โ† handlers/, middleware/ โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค โ”‚ Domain Layer โ”‚ โ† models/, services/ โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค โ”‚ Infrastructure Layer โ”‚ โ† database/, external APIs โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ ``` ### Core Components ``` api-service/ โ”œโ”€โ”€ ๐Ÿ“ cmd/api/ # ๐Ÿšช WebSocket server entry point โ”œโ”€โ”€ ๐Ÿ“ internal/ # ๐Ÿ  Core WebSocket logic โ”‚ โ”œโ”€โ”€ handlers/websocket/ # ๐Ÿ”„ WebSocket handlers & hub โ”‚ โ”œโ”€โ”€ middleware/ # ๐Ÿ›ก๏ธ Auth & validation middleware โ”‚ โ”œโ”€โ”€ models/ # ๐Ÿ“Š Data structures & validation โ”‚ โ”œโ”€โ”€ routes/ # ๐Ÿ›ฃ๏ธ API routing โ”‚ โ”œโ”€โ”€ services/ # ๐Ÿ’ผ Business logic services โ”‚ โ””โ”€โ”€ database/ # ๐Ÿ’พ Database connections โ”œโ”€โ”€ ๐Ÿ“ docs/ # ๐Ÿ“š Swagger documentation โ””โ”€โ”€ ๐Ÿ“ configs/ # โš™๏ธ Configuration files ``` ### WebSocket Hub Architecture ``` โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚ Hub โ”‚ โ† Central WebSocket manager โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค โ”‚ โ€ข Client Management โ”‚ โ† Register/unregister clients โ”‚ โ€ข Message Broadcasting โ”‚ โ† Broadcast to clients/rooms โ”‚ โ€ข Room Management โ”‚ โ† Multi-room support โ”‚ โ€ข Connection Monitoring โ”‚ โ† Track active connections โ”‚ โ€ข Database Notifications โ”‚ โ† PostgreSQL LISTEN/NOTIFY โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ ``` *** ## โšก Quick Start ### 1๏ธโƒฃ Setup Environment (2 menit) ```bash # Clone repository git clone cd api-service # Setup environment cp .env.example .env ``` ### 2๏ธโƒฃ Pilih Method Setup **๐Ÿณ Docker (Recommended)** ```bash make docker-run ``` **๐Ÿ”ง Manual Setup** ```bash # Install dependencies go mod download # Start server go run cmd/api/main.go ``` ### 3๏ธโƒฃ Setup WebSocket Client **Start Vue.js Client Example:** ```bash cd examples/clientsocket # Install dependencies npm install # Start development server npm run dev ``` ### 4๏ธโƒฃ Verify Installation | Service | URL | Status | | :-- | :-- | :-- | | **WebSocket API** | ws://localhost:8080/api/v1/ws | โœ… | | **WebSocket Client** | http://localhost:3000 | ๐ŸŒ | | **API Documentation** | http://localhost:8080/swagger/index.html | ๐Ÿ“– | | **Health Check** | http://localhost:8080/api/sistem/health | ๐Ÿ’š | *** ## ๐Ÿ” Autentikasi ### Login \& Mendapatkan Token ```bash curl -X POST http://localhost:8080/api/v1/auth/login \ -H "Content-Type: application/json" \ -d '{ "username": "admin", "password": "password" }' ``` **Response:** ```json { "access_token": "eyJhbGciOiJIUzI1NiIs...", "expires_in": 3600, "user": { "id": "123", "username": "admin", "role": "admin" } } ``` ### Menggunakan Token ```bash curl -X GET http://localhost:8080/api/v1/products \ -H "Authorization: Bearer " ``` ### Demo Accounts | Username | Password | Role | Akses | | :-- | :-- | :-- | :-- | | `admin` | `password` | Admin | Semua endpoint | | `user` | `password` | User | Read-only | *** ## ๐Ÿ“Š API Endpoints ### ๐Ÿ”„ WebSocket Endpoints #### Main WebSocket Connection | Protocol | Endpoint | Deskripsi | | :-- | :-- | :-- | | `WS` | `ws://localhost:8080/api/v1/ws` | WebSocket connection utama | **Connection Parameters:** ```javascript // Basic connection const ws = new WebSocket('ws://localhost:8080/api/v1/ws'); ``` #### WebSocket Management API | Method | Endpoint | Deskripsi | | :-- | :-- | :-- | | `GET` | `/api/websocket/stats` | WebSocket connection statistics | | `GET` | `/api/websocket/clients` | List all connected clients | | `GET` | `/api/websocket/rooms` | List all active rooms | | `POST` | `/api/websocket/broadcast` | Server-initiated broadcast | | `POST` | `/api/websocket/broadcast/room/:room` | Broadcast to specific room | | `POST` | `/api/websocket/send/:clientId` | Send message to specific client | | `POST` | `/api/websocket/cleanup/inactive` | Cleanup inactive clients | ### ๐ŸŒ Public REST Endpoints | Method | Endpoint | Deskripsi | | :-- | :-- | :-- | | `POST` | `/api/v1/auth/login` | Login pengguna | | `POST` | `/api/v1/auth/register` | Registrasi pengguna baru | | `GET` | `/api/sistem/health` | Status kesehatan API | | `GET` | `/api/sistem/info` | System information | ### ๐Ÿ”’ Protected REST Endpoints #### User Management | Method | Endpoint | Deskripsi | | :-- | :-- | :-- | | `GET` | `/api/v1/auth/me` | Profile pengguna | | `PUT` | `/api/v1/auth/me` | Update profile | *** ## ๐Ÿ› ๏ธ Development ### Code Generation (30 detik) **๐ŸŽฏ Generate CRUD Lengkap** ```bash # Generate handler untuk entity baru go run tools/general/generate-handler.go product get post put delete # Generate dengan fitur advanced go run tools/general/generate-handler.go orders get post put delete dynamic search stats ``` ### Development Commands ```bash # ๐Ÿ”ฅ Development dengan hot reload make watch # ๐Ÿงช Testing make test # Unit tests make itest # Integration tests make test-all # Semua tests # ๐Ÿ“– Update dokumentasi make docs # Generate Swagger docs # ๐Ÿ” Code quality make lint # Linting make format # Format code ``` ### Environment Configuration **๐Ÿ“ .env File:** ```bash # Database BLUEPRINT_DB_HOST=localhost BLUEPRINT_DB_PORT=5432 BLUEPRINT_DB_USERNAME=postgres BLUEPRINT_DB_PASSWORD=postgres BLUEPRINT_DB_DATABASE=api_service # JWT JWT_SECRET=your-super-secret-key-change-in-production # Application APP_ENV=development APP_PORT=8080 LOG_LEVEL=debug ``` *** ## ๐Ÿš€ Deployment ### ๐Ÿณ Docker Deployment **Development:** ```bash # Start semua services make docker-run # Stop services make docker-down # Rebuild dan restart make docker-rebuild ``` **Production:** ```bash # Build production image docker build -t api-service:prod . # Run production container docker run -d \ --name api-service \ -p 8080:8080 \ --env-file .env.prod \ api-service:prod ``` ### ๐Ÿ”ง Manual Deployment ```bash # Build aplikasi make build # Run migrations ./scripts/migrate.sh up # Start server ./bin/api-service ``` *** ## ๐Ÿ“š Dokumentasi ### ๐Ÿ“– Interactive API Documentation Kunjungi **Swagger UI** di: http://localhost:8080/swagger/index.html **Cara menggunakan:** 1. ๐Ÿ”‘ Login melalui `/auth/login` endpoint 2. ๐Ÿ“‹ Copy token dari response 3. ๐Ÿ”“ Klik tombol "Authorize" di Swagger 4. ๐Ÿ“ Masukkan: `Bearer ` 5. โœ… Test semua endpoint yang tersedia ### ๐Ÿ”„ WebSocket Client Examples #### JavaScript WebSocket Client **Basic Connection:** ```javascript // Create WebSocket connection const ws = new WebSocket('ws://localhost:8080/api/v1/ws'); // Connection opened ws.onopen = function(event) { console.log('Connected to WebSocket server'); }; // Listen for messages ws.onmessage = function(event) { const data = JSON.parse(event.data); console.log('Message received:', data); }; // Send a message function sendMessage(message) { ws.send(JSON.stringify({ type: 'broadcast', message: message })); } // Handle connection close ws.onclose = function(event) { console.log('Disconnected from WebSocket server'); }; ``` #### Vue.js Component Example ```vue ``` ### ๐Ÿงช Testing Examples **WebSocket Testing with wscat:** ```bash # Install wscat globally npm install -g wscat # Connect to WebSocket server wscat -c ws://localhost:8080/api/v1/ws # Send a message {"type": "broadcast", "message": "Hello from wscat!"} ``` **cURL for REST endpoints:** ```bash # Login TOKEN=$(curl -s -X POST http://localhost:8080/api/v1/auth/login \ -H "Content-Type: application/json" \ -d '{"username":"admin","password":"password"}' | jq -r '.access_token') # Get WebSocket statistics curl http://localhost:8080/api/websocket/stats # Broadcast message to all clients curl -X POST http://localhost:8080/api/websocket/broadcast \ -H "Content-Type: application/json" \ -d '{"type": "broadcast", "message": "Server broadcast message"}' # Get system information curl http://localhost:8080/api/sistem/info # Health check curl http://localhost:8080/api/sistem/health ``` **Response Examples:** ```json { "connected_clients": 5, "databases": ["default"], "database_health": "connected", "timestamp": 1694325600 } ``` *** ## ๐Ÿšจ Troubleshooting ### Masalah Umum **โŒ Database Connection Error** ```bash # Cek status PostgreSQL make db-status # Reset database make db-reset # Check logs make logs-db ``` **โŒ Generate Handler Gagal** - โœ… Pastikan berada di root project - โœ… Cek permission write di folder `internal/` - โœ… Verifikasi file `internal/routes/v1/routes.go` exists **โŒ Token Invalid/Expired** - ๐Ÿ”„ Login ulang untuk mendapatkan token baru - โฐ Token expire dalam 1 jam (configurable) - ๐Ÿ“ Format harus: `Bearer ` **โŒ Import Error saat Generate** - ๐Ÿงน Jalankan: `go mod tidy` - ๐Ÿ”„ Restart development server - ๐Ÿ“ Cek format import di generated files ### Debug Mode ```bash # Enable debug logging export LOG_LEVEL=debug # Run dengan verbose output make run-debug # Monitor performance make monitor ``` *** ## ๐ŸŽฏ Next Steps ### ๐Ÿ“‹ WebSocket Development Roadmap - [x] โœ… **Setup environment selesai** - [x] โœ… **Implementasi WebSocket server** - [x] โœ… **Setup Vue.js client example** - [x] โœ… **Test WebSocket functionality** - [ ] ๐Ÿ”„ **Implementasi room management** - [ ] ๐Ÿ”„ **Tambahkan authentication ke WebSocket** - [ ] ๐Ÿ”„ **Implementasi database notifications** - [ ] ๐Ÿ”„ **Tambahkan unit tests untuk WebSocket** - [ ] ๐Ÿ”„ **Setup monitoring dan observability** - [ ] ๐Ÿ”„ **Deploy ke production** ### ๐Ÿš€ Advanced WebSocket Features - **๐Ÿ”„ Database Integration** - PostgreSQL LISTEN/NOTIFY - **๐Ÿ“Š Real-time Analytics** - Connection metrics dan monitoring - **๐Ÿ”’ Enhanced Security** - Rate limiting, CORS, authentication - **๐Ÿ“ˆ Performance Optimization** - Connection pooling, message queuing - **๐Ÿ  Multi-room Support** - Advanced room management - **๐Ÿ“ฑ Mobile SDK Integration** - React Native, Flutter support - **๐ŸŒ Multi-protocol Support** - MQTT, Server-Sent Events - **๐Ÿ“ก Load Balancing** - Horizontal scaling untuk WebSocket ### ๐Ÿ› ๏ธ Immediate Next Steps 1. **Test WebSocket Connection** ```bash # Start the server go run cmd/api/main.go # Test with wscat wscat -c ws://localhost:8080/api/v1/ws ``` 2. **Try Vue.js Client Example** ```bash cd examples/clientsocket npm install npm run dev ``` 3. **Explore WebSocket Features** - Join/leave rooms - Send broadcast messages - Direct messaging between clients - Monitor connection statistics *** **โšก Total setup time: 5 menit | ๐Ÿ”„ WebSocket ready: Langsung test | ๐ŸŒ Client example: Vue.js included** > **๐Ÿ’ก Pro Tip:** Gunakan `make help` untuk melihat semua command yang tersedia ***