Documentation
¶
Overview ¶
Package client provides a fully spec-compliant HTML5 server-sent events client implementation.
Index ¶
- Variables
- type Client
- type Connection
- func (c *Connection) Connect() error
- func (c *Connection) SubscribeEvent(name string, ch chan<- Event)
- func (c *Connection) SubscribeMessages(ch chan<- Event)
- func (c *Connection) SubscribeToAll(ch chan<- Event)
- func (c *Connection) UnsubscribeEvent(name string, ch chan<- Event)
- func (c *Connection) UnsubscribeFromAll(ch chan<- Event)
- func (c *Connection) UnsubscribeMessages(ch chan<- Event)
- type Error
- type Event
- type ResponseValidator
Constants ¶
This section is empty.
Variables ¶
var DefaultClient = &Client{ HTTPClient: http.DefaultClient, DefaultReconnectionTime: time.Second * 5, ResponseValidator: DefaultValidator, }
DefaultClient is the client that is used by the free functions exported by this package. Unset properties on new clients are replaced with the ones set for the default client.
var ErrNoGetBody = errors.New("the GetBody function doesn't exist on the request")
ErrNoGetBody is a sentinel error returned when the connection cannot be reattempted due to GetBody not existing on the original request.
Functions ¶
This section is empty.
Types ¶
type Client ¶
type Client struct {
// The HTTP client to be used. Defaults to http.DefaultClient.
HTTPClient *http.Client
// A callback that's executed whenever a reconnection attempt starts.
OnRetry backoff.Notify
// A function to check if the response from the server is valid.
// Defaults to a function that checks the response's status code is 200
// and the content type is text/event-stream.
//
// If the error type returned has a Temporary or a Timeout method,
// they will be used to determine whether to reattempt the connection.
// Otherwise, the error will be considered permanent and no reconnections
// will be attempted.
ResponseValidator ResponseValidator
// The maximum number of reconnection to attempt when an error occurs.
// If MaxRetries is negative (-1), infinite reconnection attempts will be done.
// Defaults to 0 (no retries).
MaxRetries int
// The initial reconnection delay. Subsequent reconnections use a longer
// time. This can be overridden by retry values sent by the server.
// Defaults to 5 seconds.
DefaultReconnectionTime time.Duration
}
The Client struct is used to initialize new connections to different servers. It is safe for concurrent use.
After connections are created, the Connect method must be called to start receiving events.
func (*Client) NewConnection ¶
func (c *Client) NewConnection(r *http.Request) *Connection
NewConnection initializes and configures a connection. On connect, the given request is sent and if successful the connection starts receiving messages. Use the request's context to stop the connection.
If the request has a body, it is necessary to provide a GetBody function in order for the connection to be reattempted, in case of an error. Using readers such as bytes.Reader, strings.Reader or bytes.Buffer when creating a request using http.NewRequestWithContext will ensure this function is present on the request.
type Connection ¶
type Connection struct {
// contains filtered or unexported fields
}
Connection is a connection to an events stream. Created using the Client struct, a Connection processes the incoming events and sends them to the subscribed channels. If the connection to the server temporarily fails, the connection will be reattempted. Retry values received from servers will be taken into account.
func NewConnection ¶
func NewConnection(r *http.Request) *Connection
NewConnection creates a connection using the default client.
func (*Connection) Connect ¶
func (c *Connection) Connect() error
Connect sends the request the connection was created with to the server and, if successful, it starts receiving events. The caller goroutine is blocked until the request's context is done or an error occurs.
Connect returns a nil error on success. On non-nil errors, the connection is reattempted for the number of times the Client is configured with, using an exponential backoff that has the initial time set to either the client's default value or to the retry value received from the server. If an error is permanent (e.g. no internet connection), no retries are done. All errors returned are of type *client.Error.
After Connect returns, all subscriptions will be closed. Make sure to wait for the subscribers' goroutines to exit, as they may still be running after Connect has returned. Connect cannot be called twice for the same connection.
func (*Connection) SubscribeEvent ¶
func (c *Connection) SubscribeEvent(name string, ch chan<- Event)
SubscribeEvent subscribes the given channel to all the events with the provided name (the event field has the value given here).
func (*Connection) SubscribeMessages ¶
func (c *Connection) SubscribeMessages(ch chan<- Event)
SubscribeMessages subscribes the given channel to all events that are unnamed (no event field is present).
func (*Connection) SubscribeToAll ¶
func (c *Connection) SubscribeToAll(ch chan<- Event)
SubscribeToAll subscribes the given channel to all events, named and unnamed. If the channel is already subscribed to some events it won't receive those events twice.
func (*Connection) UnsubscribeEvent ¶
func (c *Connection) UnsubscribeEvent(name string, ch chan<- Event)
UnsubscribeEvent unsubscribes al already subscribed channel from the events with the provided name. If the channel is not subscribed to any other events, it will be closed. Don't call this method from the goroutine that receives from the channel, as it may result in a deadlock!
func (*Connection) UnsubscribeFromAll ¶
func (c *Connection) UnsubscribeFromAll(ch chan<- Event)
UnsubscribeFromAll unsubscribes an already subscribed channel from all the events it is subscribed to. After unsubscription the channel will be closed. The channel doesn't have to be subscribed using the SubscribeToAll method in order for this method to unsubscribe it. Don't call this method from the goroutine that receives from the channel, as it may result in a deadlock!
func (*Connection) UnsubscribeMessages ¶
func (c *Connection) UnsubscribeMessages(ch chan<- Event)
UnsubscribeMessages unsubscribes an already subscribed channel from unnamed events. If the channel is not subscribed to any other events, it will be closed. Don't call this method from the goroutine that receives from the channel, as it may result in a deadlock!
type Error ¶
type Error struct {
// The request for which the connection failed.
Req *http.Request
// The reason the operation failed.
Err error
// The reason why the request failed.
Reason string
}
Error is the type that wraps all the connection errors that occur.
type Event ¶
type Event struct {
// The last non-empty ID of all the events received. This may not be
// the ID of the latest event!
LastEventID string
// The event's name. It is empty if the eventName is unnamed.
Name string
// The events's payload in raw form. Use the String method if you need it as a string.
Data []byte
}
The Event struct represents an event sent to the helloworld_client by the server.
type ResponseValidator ¶
The ResponseValidator type defines the type of the function that checks whether server responses are valid, before starting to read events from them. See the Client's documentation for more info.
var DefaultValidator ResponseValidator = func(r *http.Response) error { if r.StatusCode != http.StatusOK { return fmt.Errorf("expected status code %d, received %d", http.StatusOK, r.StatusCode) } if rc, ec := r.Header.Get("Content-Type"), "text/event-stream"; rc != ec { return fmt.Errorf("expected content type %q, received %q", ec, rc) } return nil }
DefaultValidator is the default response validation function. It checks the content type to be text/event-stream and the response status code to be 200 OK.
var NoopValidator ResponseValidator = func(_ *http.Response) error { return nil }
NoopValidator is a validator function that treats all responses as valid.