A real-time WebSocket-based chat server built with Go, following the "Let's Go Further" book's project structure.
- 🚀 Real-time messaging using WebSockets
- 💬 Single global chat room
- 📸 Media sharing support (images and files)
- 🔄 No data persistence (ephemeral chat)
- 🛡️ Rate limiting and CORS support
- 📝 Structured JSON logging
- 🎯 Clean architecture following Go best practices
go-chat-server/
├── bin/ # Compiled binaries
├── cmd/
│ └── api/ # Application entry point and HTTP handlers
├── internal/
│ ├── chat/ # Chat hub and client logic
│ ├── jsonlog/ # Structured JSON logger
│ └── validator/ # Input validation helpers
├── go.mod # Module dependencies
└── Makefile # Build automation
- Go 1.21 or higher
- Clone the repository:
cd /Users/sohail/Developer/go-chat-server- Install dependencies:
go mod download- Run the server:
make run/api
# or
go run ./cmd/apiThe server will start on http://localhost:4000
GET /v1/healthcheck- Health check endpointGET /v1/ws- WebSocket endpoint for chat
Messages are sent as JSON over WebSocket:
{
"type": "text|image|file|system",
"username": "YourUsername",
"content": "Your message content",
"timestamp": "2026-02-11T12:00:00Z",
"metadata": {
"filename": "image.jpg",
"mimetype": "image/jpeg",
"size": 12345
}
}text- Regular text messageimage- Image (base64 encoded or URL)file- File attachment (base64 encoded or URL)system- System notification
Open your browser console and run:
const ws = new WebSocket('ws://localhost:4000/v1/ws');
ws.onopen = () => {
console.log('Connected to chat server');
// Send a text message
ws.send(JSON.stringify({
type: 'text',
username: 'TestUser',
content: 'Hello, World!'
}));
};
ws.onmessage = (event) => {
const message = JSON.parse(event.data);
console.log('Received:', message);
};
ws.onerror = (error) => {
console.error('WebSocket error:', error);
};
ws.onclose = () => {
console.log('Disconnected from chat server');
};make run/apimake build/apimake auditThe server accepts the following command-line flags:
-port- Server port (default: 4000)-env- Environment (development|staging|production)-cors-trusted-origins- Trusted CORS origins (can be specified multiple times)
Example:
go run ./cmd/api -port=8080 -env=production -cors-trusted-origins="https://example.com"The application follows the "Let's Go Further" book's architecture:
- cmd/api - Application-specific code (HTTP server, routes, handlers)
- internal - Reusable packages that cannot be imported by external projects
- Graceful shutdown - Properly handles SIGINT and SIGTERM signals
- Middleware chain - Panic recovery, rate limiting, and CORS
- Structured logging - JSON-formatted logs for easy parsing
MIT