Documentation
¶
Overview ¶
Package long_polling provides HTTP long polling server and client implementations.
This package enables real-time communication using HTTP long polling patterns, allowing clients to receive server-side events with minimal latency without WebSocket connections. It wraps golongpoll for easy server setup and client communication.
Features ¶
- Long polling server with configurable timeouts
- Event subscription and publishing
- File-based persistence for event durability
- Custom middleware support for authentication and validation
- Client helpers for subscription and publishing
Basic Client Example ¶
response, err := long_polling.Subscription(
"http://localhost:8080/events",
nil,
long_polling.SubscriptionRequest{
Category: "notifications",
TimeoutSeconds: 60,
},
"", "", nil,
)
Package long_polling provides HTTP long polling server and client implementations.
This package enables real-time communication using HTTP long polling patterns, allowing clients to receive server-side events with minimal latency without WebSocket connections. It wraps golongpoll for easy server setup and client communication.
Features ¶
- Long polling server with configurable timeouts
- Event subscription and publishing
- File-based persistence for event durability
- Custom middleware support for authentication and validation
- Client helpers for subscription and publishing
Basic Server Example ¶
server := &long_polling.Server{}
err := server.Start(long_polling.ServerInfo{
Address: ":8080",
TimeoutSeconds: 120,
SubscriptionURI: "/events",
PublishURI: "/publish",
}, long_polling.FilePersistorInfo{Use: false}, nil)
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Publish ¶
func Publish(rawURL string, timeout time.Duration, header map[string][]string, publishRequest PublishRequest, username, password string, transport *net_http.Transport) (http.Response, error)
Publish publishes an event to the long polling server.
This function sends an event to the server, which distributes it to all subscribed clients in the specified category.
Parameters ¶
- rawURL: Server publish endpoint URL (e.g., "http://localhost:8080/publish")
- timeout: Maximum duration to wait for publish operation
- header: Optional HTTP headers (e.g., custom headers or authorization)
- publishRequest: Event data (category and data payload)
- username: Optional HTTP basic authentication username
- password: Optional HTTP basic authentication password
- transport: Optional custom HTTP transport for connection pooling or proxies
Returns ¶
- http.Response: HTTP response with headers, status code, and body
- error: Error if request fails, nil on successful publish
Behavior ¶
The publish request:
- Sends event to server via POST request
- Server assigns unique event ID and timestamp
- Event is queued for subscribed clients
- Returns immediately (non-blocking)
Examples ¶
Publish notification:
response, err := long_polling.Publish(
"http://localhost:8080/publish",
10 * time.Second,
nil,
long_polling.PublishRequest{
Category: "notifications",
Data: `{"message": "Hello"}`
},
"", "", nil,
)
Types ¶
type FilePersistorInfo ¶
type FilePersistorInfo struct {
Use bool
FileName string
WriteBufferSize int
WriteFlushPeriodSeconds int
}
FilePersistorInfo is file persistor information.
type PublishRequest ¶
PublishRequest is publish request information.
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server is a struct that provides server related methods.
func (*Server) Start ¶
func (s *Server) Start(serverInfo ServerInfo, filePersistorInfo FilePersistorInfo, listenAndServeFailureFunc func(err error)) error
Start initializes and starts the long polling server.
This method creates a long polling manager, sets up subscription and publish handlers, and starts the HTTP server. It supports optional file persistence for event durability across server restarts.
Parameters ¶
- serverInfo: Server configuration including address, timeout, URIs, and middleware
- filePersistorInfo: File persistence configuration for event durability
- listenAndServeFailureFunc: Optional callback for listen and serve failures
Returns ¶
- error: Error if server initialization or start fails, nil on success
Behavior ¶
The server creates two endpoints:
- Subscription endpoint (GET): Clients subscribe for events on specific categories
- Publish endpoint (POST): Server or authorized clients publish events
Custom handlers can be provided to run before subscription or publish operations, enabling authentication, validation, or logging. If a handler returns false, the request is rejected.
Examples ¶
Basic server:
server := &long_polling.Server{}
err := server.Start(long_polling.ServerInfo{
Address: ":8080",
TimeoutSeconds: 120,
SubscriptionURI: "/events",
PublishURI: "/publish",
}, long_polling.FilePersistorInfo{Use: false}, nil)
func (*Server) Stop ¶
Stop gracefully shuts down the long polling server.
This method stops the HTTP server with a timeout for existing connections and shuts down the long polling manager, ensuring all events are flushed if file persistence is enabled.
Parameters ¶
- shutdownTimeout: Maximum duration to wait for active connections to close
Returns ¶
- error: Error if shutdown fails, nil on successful shutdown
Behavior ¶
The shutdown process:
- Stops accepting new connections
- Waits up to shutdownTimeout for active connections to close
- Shuts down the long polling manager (flushes pending events)
- Closes all resources
If the timeout is reached before all connections close, the server forcibly terminates remaining connections.
Examples ¶
Graceful shutdown with 10 second timeout:
err := server.Stop(10 * time.Second)
if err != nil {
log.Printf("Shutdown error: %v", err)
}
type ServerInfo ¶
type ServerInfo struct {
Address string
TimeoutSeconds int
SubscriptionURI string
HandlerToRunBeforeSubscription func(w http.ResponseWriter, r *http.Request) bool
PublishURI string
HandlerToRunBeforePublish func(w http.ResponseWriter, r *http.Request) bool
}
ServerInfo is server information.
type SubscriptionRequest ¶
type SubscriptionRequest struct {
Category string `url:"category"`
TimeoutSeconds int `url:"timeout"`
SinceTime int64 `url:"since_time,omitempty"`
LastID string `url:"last_id,omitempty"`
}
SubscriptionRequest is subscription request information.
type SubscriptionResponse ¶
type SubscriptionResponse struct {
Header net_http.Header
StatusCode int
Events []struct {
Timestamp int64 `json:"timestamp"`
Category string `json:"category"`
ID string `json:"id"`
Data string `json:"data"`
} `json:"events"`
}
SubscriptionResponse is subscription response information.
func Subscription ¶
func Subscription(rawURL string, header map[string][]string, request SubscriptionRequest, username, password string, transport *net_http.Transport) (SubscriptionResponse, error)
Subscription subscribes to server events using HTTP long polling.
This function sends a long polling request to the server and waits for events in the specified category. The request blocks until an event occurs or the timeout expires.
Parameters ¶
- rawURL: Server subscription endpoint URL (e.g., "http://localhost:8080/events")
- header: Optional HTTP headers (e.g., custom headers or authorization)
- request: Subscription parameters (category, timeout, since_time, last_id)
- username: Optional HTTP basic authentication username
- password: Optional HTTP basic authentication password
- transport: Optional custom HTTP transport for connection pooling or proxies
Returns ¶
- SubscriptionResponse: Response containing events and metadata
- error: Error if request fails or response parsing fails, nil on success
Behavior ¶
The subscription request includes:
- category: Event category to subscribe to
- timeout: Maximum seconds to wait for events
- since_time: Optional timestamp to retrieve events since (Unix milliseconds)
- last_id: Optional last event ID to retrieve events after
The response includes:
- Header: HTTP response headers
- StatusCode: HTTP status code (200 for events, 204 for timeout)
- Events: Array of events (empty if timeout)
Examples ¶
Basic subscription:
response, err := long_polling.Subscription(
"http://localhost:8080/events",
nil,
long_polling.SubscriptionRequest{
Category: "notifications",
TimeoutSeconds: 60,
},
"", "", nil,
)