The term "comet" refers to web techniques that allow servers to push data to a web browser. This is in contrast to HTTP's poll-only REST architecture.
One way to simulate push behavior via HTTP is to use a long poll: an HTTP request which waits for some even before responding.
Long-polling via XMLHttpRequest is straightforward. Basically, the client polls the server like normal. The server will not reply until a corresponding event has occurred. When the server finally responds, a client-side callback is triggered, and another request is immediately. This simple helper function demonstrates the idea:
The server must be designed to wait until some event occurs before responding to the HTTP request. This can be implemented via semaphores, locks, etc in other languages. In Go, channels work great:
The HTTP response handler will not write the response until the message channel is non-empty. This way, clients can long-poll for the message and be notified instantly when it arrives.
The message channel can be filled by other clients:
In the above response handler, the client is expected to POST a message, which will be instantly delivered to another long-polling client.
With named channels, it is possible to notify specific clients:
With non-zero-length channels, you can enable your server to queue messages for off-line clients.
However, there is a major problem with the above code. The PollResponse handler might continue to block even after the client has disconnected. Unless a message arrives for the client at some point, the response handler might continue to block indefinitely.
To solve this problem, you can launch an extra goroutine to send a timeout message to the response handler:
Perhaps when the http package matures, there will be a per-request channel for detecting "client disconnected" events.