A lightweight and clean implementation of Long-Polling using the Gin framework in Go.
This project demonstrates how to build a near real-time communication pattern between clients and the server.
This is an educational project for learning long-polling, which can help understand socket-based communication.
first clone:
git clone https://github.com/Serajian/GO-long-polling-gin.git
cd GO-long-polling-ginget requires:
go mod tidyrun app:
go run main.goTerminal 1:
curl -N http://localhost:8090/poll/u1Terminal 2 (within 30s):
curl -X POST http://localhost:8090/send/u1 \
-H "Content-Type: application/json" \
-d '{"message":"ping!"}'
:id is the unique client identifier (e.g., user-123).
The server waits up to 30 seconds. If no message is sent, a 504 timeout is returned.
Successful response:
HTTP/1.1 200 OK
{
"message": "hello from server"
}Timeout:
HTTP/1.1 504 Gateway Timeout
{
"error": "timeout"
}
Request body (JSON):
{
"message": "hello from server"
}
Response:
HTTP/1.1 200 OK
{
"status": "message sent"
}
Note: If no client is currently waiting with that id, the message will be dropped (by design of long-polling).
🗺️ Comparison with Other Real-Time Patterns
- Simple Polling: Client sends requests repeatedly (high overhead).
- Long-Polling (this project): One request stays open until message or timeout.
- WebSocket: Persistent two-way connection; best for high-frequency low-latency messaging.
- SSE (Server-Sent Events): One-way streaming from server to client.