Documentation
¶
Overview ¶
Package sse provides utilities for creating and consuming fully spec-compliant HTML5 server-sent events streams.
The central piece of a server's implementation is the Provider interface. A Provider describes a publish-subscribe system that can be used to implement messaging for the SSE protocol. This package already has an implementation, called Joe, that is the default provider for any server. Abstracting the messaging system implementation away allows servers to use any arbitrary provider under the same interface. The default provider will work for simple use-cases, but where scalability is required, one will look at a more suitable solution. Adapters that satisfy the Provider interface can easily be created, and then plugged into the server instance. Events themselves are represented using the Message type.
On the client-side, we use the Client struct to create connections to event streams. Using an `http.Request` we instantiate a Connection. Then we subscribe to incoming events using callback functions, and then we establish the connection by calling the Connection's Connect method.
Index ¶
- Constants
- Variables
- type Client
- type Connection
- type ConnectionError
- type Event
- type EventCallback
- type EventCallbackRemover
- type EventID
- func (i EventID) IsSet() bool
- func (i *EventID) MarshalJSON() ([]byte, error)
- func (i *EventID) MarshalText() ([]byte, error)
- func (i *EventID) Scan(src interface{}) error
- func (i EventID) String() string
- func (i *EventID) UnmarshalJSON(data []byte) error
- func (i *EventID) UnmarshalText(data []byte) error
- func (i EventID) Value() (driver.Value, error)
- type FiniteReplayProvider
- type Joe
- type JoeConfig
- type Logger
- type Message
- func (e *Message) AppendData(chunks ...[]byte)
- func (e *Message) AppendText(chunks ...string)
- func (e *Message) Clone() *Message
- func (e *Message) Comment(comments ...string)
- func (e *Message) ExpiresAt() time.Time
- func (e *Message) ID() EventID
- func (e *Message) MarshalText() ([]byte, error)
- func (e *Message) SetExpiry(t time.Time)
- func (e *Message) SetID(id EventID)
- func (e *Message) SetName(name string) bool
- func (e *Message) SetRetry(duration time.Duration)
- func (e *Message) SetTTL(d time.Duration)
- func (e *Message) String() string
- func (e *Message) UnmarshalText(p []byte) error
- func (e *Message) WriteTo(w io.Writer) (int64, error)
- type Provider
- type ReplayProvider
- type ReplayProviderWithGC
- type ResponseValidator
- type Server
- type ServerOption
- type Subscription
- type SubscriptionCallback
- type UnmarshalError
- type UpgradedRequest
- type ValidReplayProvider
Constants ¶
const DefaultTopic = ""
DefaultTopic is the identifier for the topic that is implied when no topics are specified for a Subscription or a Message. Providers are required to implement this behavior to ensure handlers don't break if providers are changed.
Variables ¶
var DefaultClient = &Client{ HTTPClient: http.DefaultClient, DefaultReconnectionTime: time.Second * 5, ResponseValidator: DefaultValidator, }
DefaultClient is the client that is used when creating a new connection using the NewConnection function. Unset properties on new clients are replaced with the ones set for the default client.
var ErrIDUnset = errors.New("tried to marshal to text an unset ID")
ErrIDUnset is returned when calling MarshalText for an unset ID.
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.
var ErrProviderClosed = errors.New("go-sse.server: provider is closed")
ErrProviderClosed is a sentinel error returned by providers when any operation is attempted after the provider is closed.
var ErrUnexpectedEOF = parser.ErrUnexpectedEOF
ErrUnexpectedEOF is returned when unmarshaling a Message from an input that doesn't end in a newline.
var ErrUpgradeUnsupported = errors.New("go-sse.server: upgrade unsupported")
ErrUpgradeUnsupported is returned when a request can't be upgraded to support server-sent events.
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.
Connections must not be copied after they are created.
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 *ConnectionError.
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, cb EventCallback) EventCallbackRemover
SubscribeEvent subscribes the given callback to all the events with the provided name (the event field has the value given here). Remove the callback by calling the returned function.
func (*Connection) SubscribeMessages ¶
func (c *Connection) SubscribeMessages(cb EventCallback) EventCallbackRemover
SubscribeMessages subscribes the given callback to all unnamed events (none or empty event field). Remove the callback by calling the returned function.
func (*Connection) SubscribeToAll ¶
func (c *Connection) SubscribeToAll(cb EventCallback) EventCallbackRemover
SubscribeToAll subscribes the given callbcak to all events, named and unnamed. Remove the callback by calling the returned function.
type ConnectionError ¶
type ConnectionError 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
}
ConnectionError is the type that wraps all the connection errors that occur.
func (*ConnectionError) Error ¶
func (e *ConnectionError) Error() string
func (*ConnectionError) Temporary ¶
func (e *ConnectionError) Temporary() bool
Temporary returns whether the underlying error is temporary.
func (*ConnectionError) Timeout ¶
func (e *ConnectionError) Timeout() bool
Timeout returns whether the underlying error is caused by a timeout.
func (*ConnectionError) Unwrap ¶
func (e *ConnectionError) Unwrap() error
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 client by a server.
type EventCallback ¶ added in v0.3.0
type EventCallback func(Event)
EventCallback is a function that is used to receive events from a Connection.
type EventCallbackRemover ¶ added in v0.3.0
type EventCallbackRemover func()
EventCallbackRemover is a function that removes an already registered callback from a connection. Calling it multiple times is a no-op.
type EventID ¶
type EventID struct {
// contains filtered or unexported fields
}
The EventID struct represents any valid event ID value. IDs must be passed around as values, not as pointers! They can also safely be used as map keys.
func MustEventID ¶
MustEventID is the same as NewEventID, but it panics if the input isn't a valid ID.
func NewEventID ¶
NewEventID creates an EventID value. It also returns a flag that indicates whether the input is a valid ID. A valid ID must not have any newlines. If the input is not valid, an unset (invalid) ID is returned.
func (*EventID) MarshalJSON ¶
MarshalJSON returns a JSON representation of the ID's value if it is set. It otherwise returns the representation of the JSON null value.
func (*EventID) MarshalText ¶
MarshalText returns a copy of the ID's value if it is set. It returns an error when trying to marshal an unset ID.
func (*EventID) Scan ¶
Scan implements the sql.Scanner interface. IDs can be scanned from:
- nil interfaces (result: unset ID)
- byte slice
- string
func (EventID) String ¶
String returns the ID's value. The value may be an empty string, make sure to check if the ID is set before using the value.
func (*EventID) UnmarshalJSON ¶
UnmarshalJSON sets the ID's value to the given JSON value if the value is a string and it doesn't contain any null bytes. The previous value is discarded if the operation fails.
func (*EventID) UnmarshalText ¶
UnmarshalText sets the ID's value to the given string, if valid. If the input is invalid, the previous value is discarded.
type FiniteReplayProvider ¶
type FiniteReplayProvider struct {
// contains filtered or unexported fields
}
FiniteReplayProvider is a replay provider that replays at maximum a certain number of events. GC is a no-op for this provider, as when the maximum number of values is reached and a new value has to be appended, old values are removed from the buffer.
func NewFiniteReplayProvider ¶
func NewFiniteReplayProvider(count int, autoIDs ...bool) *FiniteReplayProvider
NewFiniteReplayProvider creates a replay provider that can hold a maximum number of events at once. The events' expiry times are not considered, as the oldest events are removed anyway when the provider has buffered the maximum number of events. The events must have an ID unless the provider is constructed with the autoIDs flag.
func (*FiniteReplayProvider) Put ¶
func (f *FiniteReplayProvider) Put(message **Message)
Put puts a message into the provider's buffer. If there are more messages than the maximum number, the oldest message is removed.
func (*FiniteReplayProvider) Replay ¶
func (f *FiniteReplayProvider) Replay(subscription Subscription) bool
Replay replays the messages in the buffer to the listener. It doesn't take into account the messages' expiry times.
type Joe ¶
type Joe struct {
// contains filtered or unexported fields
}
Joe is a basic server provider that synchronously executes operations by queueing them in channels. Events are also sent synchronously to subscribers, so if a subscriber's callback blocks, the others have to wait.
Joe optionally supports event replaying with the help of a replay provider.
If due to some unexpected scenario (the replay provider has a bug, for example) a panic occurs, Joe will remove all subscribers, so requests don't hang.
He serves simple use-cases well, as he's light on resources, and does not require any external services. Also, he is the default provider for Servers.
func NewJoe ¶
NewJoe creates and starts a Joe (the default provider for servers). You can optionally pass a JoeConfig if you want to use a ReplayProvider with Joe.
type JoeConfig ¶
type JoeConfig struct {
// An optional replay provider that Joe uses to resend older messages to new subscribers.
ReplayProvider ReplayProvider
// An optional interval at which Joe triggers a cleanup of expired messages, if the replay provider supports it.
// See the desired provider's documentation to determine if periodic cleanup is necessary.
ReplayGCInterval time.Duration
}
JoeConfig is used to optionally configure a replay provider for Joe.
type Logger ¶ added in v0.4.1
type Logger interface {
Printf(format string, args ...interface{})
}
The Logger interface describes an object that can be used for logging.
type Message ¶
type Message struct {
Topic string
// contains filtered or unexported fields
}
Message is the representation of a single message sent from the server to its clients.
A Message is made of a single event, which is sent to each client, and other metadata about the message itself: its expiry time and topic.
Topics are used to filter which events reach which clients. If a client subscribes to a certain set of topics, but a message's topic is not part of that set, then the underlying event of the message does not reach the client.
The message's expiry time can be used when replaying messages to new clients. If a message is expired, then it is not sent. Replay providers will usually make use of this.
func (*Message) AppendData ¶
AppendData creates multiple data fields on the message's event from the given byte slices.
Server-sent events are not suited for binary data: the event fields are delimited by newlines, where a newline can be a LF, CR or CRLF sequence. When the client interprets the fields, it joins multiple data fields using LF, so information is altered. Here's an example:
initial payload: This is a\r\nmultiline\rtext.\nIt has multiple\nnewline\r\nvariations. data sent over the wire: data: This is a data: multiline data: text. data: It has multiple data: newline data: variations data received by client: This is a\nmultiline\ntext.\nIt has multiple\nnewline\nvariations.
Each line prepended with "data:" is a field; multiple data fields are joined together using LF as the delimiter. If you attempted to send the same payload without prepending the "data:" prefix, like so:
data: This is a multiline text. It has multiple newline variations
there would be only one data field (the first one). The rest would be different fields, named "multiline", "text.", "It has multiple" etc., which are invalid fields according to the protocol.
Besides, the protocol explicitly states that event streams must always be UTF-8 encoded: https://html.spec.whatwg.org/multipage/server-sent-events.html#parsing-an-event-stream.
Still, if you need to send binary data, you can use a Base64 encoder or any other encoder that does not output any newline characters (\r or \n) and then append the resulted byte slices.
func (*Message) AppendText ¶
AppendText creates multiple data fields on the message's event from the given strings. It uses the unsafe package to convert the string to a byte slice, so no allocations are made. See the AppendData method's documentation for details about the data field type.
func (*Message) Comment ¶
Comment creates a comment field on the message's event. If it spans multiple lines, new comment lines are created.
func (*Message) MarshalText ¶
MarshalText writes the standard textual representation of the message's event. Marshalling and unmarshalling will not result in a message with an event that has the same fields: comment fields will not be unmarshalled, and expiry time and topic will be lost.
Use the WriteTo method if you don't need the byte representation.
The representation is written to a bytes.Buffer, which means the error is always nil. If the buffer grows to a size bigger than the maximum allowed, MarshalText will panic. See the bytes.Buffer documentation for more info.
func (*Message) SetExpiry ¶
SetExpiry sets the message's expiry time to the given timestamp.
This is not sent to the clients. The expiry time can be used when implementing event replay providers, to see if an event is still valid for replay.
func (*Message) SetName ¶
SetName sets the message's event's name.
A Name cannot have multiple lines. If it has, the function will return false.
func (*Message) SetRetry ¶
SetRetry creates a field on the message's event that tells the client to set the event stream reconnection time to the number of milliseconds it provides.
func (*Message) SetTTL ¶
SetTTL sets the message's expiry time to a timestamp after the given duration from the current time.
This is not sent to the clients. The expiry time can be used when implementing event replay providers, to see if an event is still valid for replay.
func (*Message) String ¶
String writes the message's event standard textual representation to a strings.Builder and returns the resulted string. It may panic if the representation is too long to be buffered.
Use the WriteTo method if you don't actually need the string representation.
func (*Message) UnmarshalText ¶
UnmarshalText extracts the first event found in the given byte slice into the receiver. The receiver is always reset to the message's default value before unmarshaling, so always use a new Message instance if you don't want to overwrite data.
Unmarshaling ignores comments and fields with invalid names. If no valid fields are found, an error is returned. For a field to be valid it must end in a newline - if the last field of the event doesn't end in one, an error is returned.
All returned errors are of type UnmarshalError.
type Provider ¶
type Provider interface {
// Subscribe to the provider. The context is used to remove the subscriber automatically
// when it is done. Errors returned by the subscription's callback function must be returned
// by Subscribe.
//
// Providers can assume that the topics list for a subscription has at least one topic.
Subscribe(ctx context.Context, subscription Subscription) error
// Publish a message to all the subscribers that are subscribed to the message's topic.
Publish(message *Message) error
// Stop the provider. Calling Stop will clean up all the provider's resources and
// make Subscribe and Publish fail with an error. All the listener channels will be
// closed and any ongoing publishes will be aborted.
//
// Calling Stop multiple times does nothing but return ErrProviderClosed.
Stop() error
}
A Provider is a publish-subscribe system that can be used to implement a HTML5 server-sent events protocol. A standard interface is required so HTTP request handlers are agnostic to the provider's implementation.
Providers are required to be thread-safe.
After Stop is called, trying to call any method of the provider must return ErrProviderClosed. The providers may return other implementation-specific errors too, but the close error is guaranteed to be the same across providers.
type ReplayProvider ¶
type ReplayProvider interface {
// Put adds a new event to the replay buffer. The message's event may be modified by
// the provider, if it sets an ID.
//
// The Put operation may be executed by the replay provider in another goroutine only if
// it can ensure that any Replay operation called after the Put goroutine is started
// can replay the new received message. This also requires the replay provider implementation
// to be thread-safe.
//
// Replay providers are not required to guarantee that after Put returns the new events
// can be replayed. If an error occurs and retrying the operation would block for too
// long, it can be aborted. The errors aren't returned as the server providers won't be able
// to handle them in a useful manner anyway.
Put(message **Message)
// Replay sends to a new subscriber all the valid events received by the provider
// since the event with the listener's ID. If the ID the listener provides
// is invalid, the provider should not replay any events.
//
// Replay operations must be executed in the same goroutine as the one it is called in.
// Other goroutines may be launched from inside the Replay method, but the events must
// be sent to the listener in the same goroutine that Replay is called in.
//
// The returned value indicates whether messages were replayed successfully. If no messages
// were replayed (invalid ID or no messages to replay) it must return true. It returns false
// only if the subscription's callback returns false.
Replay(subscription Subscription) bool
}
A ReplayProvider is a type that can replay older published events to new subscribers. Replay providers use event IDs, the topics the events were published to and optionally the events' expiration times or any other criteria to determine which are valid for replay.
While providers can require events to have IDs beforehand, they can also set the IDs themselves, automatically - it's up to the implementation. Providers should ignore events without IDs, if they require IDs to be set.
Replay providers are not required to be thread-safe - server providers are required to ensure only one operation is executed on the replay provider at any given time. Server providers may not execute replay operation concurrently with other operations, so make sure any action on the replay provider blocks for as little as possible. If a replay provider is thread-safe, some operations may be run in a separate goroutine - see the interface's method documentation.
Executing actions that require waiting for a long time on I/O, such as HTTP requests or database calls must be handled with great care, so the server provider is not blocked. Reducing them to the minimum by using techniques such as caching or by executing them in separate goroutines is recommended, as long as the implementation fulfills the requirements.
If not specified otherwise, the errors returned are implementation-specific.
type ReplayProviderWithGC ¶ added in v0.3.0
type ReplayProviderWithGC interface {
ReplayProvider
// GC triggers a cleanup. After GC returns, all the messages that are invalid according
// to the provider's criteria should be impossible to replay again.
//
// If GC returns an error, the provider is not required to try to trigger another
// GC ever again. Make sure that before you return a non-nil value you handle
// temporary errors accordingly, with blocking as shortly as possible.
//
// If the replay provider implementation is thread-safe the GC operation can be executed in another goroutine.
GC() error
}
ReplayProviderWithGC is a ReplayProvider that must have invalid messages cleaned up from time to time. This may be the case for a provider that replays messages that are not expired: at a certain interval, expired messages must be removed from the provider to free up resources.
Providers must check if replay providers implement this interface, so they can call GC accordingly.
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.
Returning an error type that implements the Temporary method will tell the client to reattempt the connection. This can be useful if you're being rate limited (response code 429), for example.
var DefaultValidator ResponseValidator = func(r *http.Response) error { if r.StatusCode != http.StatusOK { return fmt.Errorf("expected status code %d %s, received %d %s", http.StatusOK, http.StatusText(http.StatusOK), r.StatusCode, http.StatusText(r.StatusCode)) } cts := r.Header.Get("Content-Type") ct := contentType(cts) if expected := "text/event-stream"; ct != expected { return fmt.Errorf("expected content type to have %q, received %q", expected, cts) } return nil }
DefaultValidator is the default client response validation function. As per the spec, It checks the content type to be text/event-stream and the response status code to be 200 OK.
If this validator fails, errors are considered permanent. No retry attempts are made.
See https://html.spec.whatwg.org/multipage/server-sent-events.html#sse-processing-model.
var NoopValidator ResponseValidator = func(_ *http.Response) error { return nil }
NoopValidator is a client response validator function that treats all responses as valid.
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
A Server is mostly a convenience wrapper around a provider. It implements the http.Handler interface and has some methods for calling the underlying provider's methods.
When creating a server, if no provider is specified using the WithProvider option, the Joe provider found in this package with no replay provider is used.
func NewServer ¶
func NewServer(options ...ServerOption) *Server
NewServer creates a new server using the specified provider. If no provider is given, Joe with no replay provider is used.
func (*Server) Publish ¶
Publish sends the event to all subscribes that are subscribed to the topic the event is published to. The topic is optional - if none is specified, the event is published to the default topic.
func (*Server) ServeHTTP ¶
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP implements a default HTTP handler for a server.
This handler upgrades the request, subscribes it to the server's provider and starts sending incoming events to the client, while logging any write errors. It also sends the Last-Event-ID header's value, if present.
If the request isn't upgradeable, it writes a message to the client along with an 500 Internal Server ConnectionError response code. If on subscribe the provider returns an error, it writes the error message to the client and a 500 Internal Server ConnectionError response code.
If you need different behavior, you can create a custom handler.
func (*Server) Shutdown ¶
Shutdown closes all the connections and stops the server. Publish operations will fail with the error sent by the underlying provider. NewServer requests will be ignored.
Call this method when shutting down the HTTP server using http.Server's RegisterOnShutdown method. Not doing this will result in the server never shutting down or connections being abruptly stopped.
The error returned is the one returned by the underlying provider's Stop method.
func (*Server) Subscribe ¶
func (s *Server) Subscribe(ctx context.Context, callback SubscriptionCallback, lastEventID EventID, topics ...string) error
Subscribe subscribes the given callback to the specified topics. It is unsubscribed when the context is closed or the server is shut down. If no topic is specified, the channel is subscribed to the default topic.
type ServerOption ¶
type ServerOption func(*Server)
A ServerOption configures a certain property of a given Server.
func WithLogger ¶ added in v0.4.1
func WithLogger(logger Logger) ServerOption
WithLogger is an option that sets a custom logger for a given Server. The default logger is the one provided by the standard log package.
func WithProvider ¶
func WithProvider(provider Provider) ServerOption
WithProvider is an option that sets a custom provider for a given Server. The default provider is Joe without any ReplayProvider, if this option isn't given.
type Subscription ¶
type Subscription struct {
// A non-nil function that is called for each new event. The callback of a single subscription will
// never be called in parallel, but callbacks from multiple subscriptions may be called in parallel.
Callback SubscriptionCallback
// An optional last event ID indicating the event to resume the stream from.
// The events will replay starting from the first valid event sent after the one with the given ID.
// If the ID is invalid replaying events will be omitted and new events will be sent as normal.
LastEventID EventID
// The topics to receive message from. If no topic is specified, a default topic is implied.
// Topics are orthogonal to event names. They are used to filter what the server sends to each client.
//
// If using a Provider directly, without a Server instance, you must specify at least one topic.
// The Server automatically adds the default topic if no topic is specified.
Topics []string
}
The Subscription struct is used to subscribe to a given provider.
type SubscriptionCallback ¶ added in v0.3.0
SubscriptionCallback is a function that is called when a subscriber receives a message. If this callback returns false, the provider must remove the subscription.
type UnmarshalError ¶
type UnmarshalError struct {
Reason error
FieldName string
// The value of the invalid field. This is a copy of the original value.
FieldValue string
}
UnmarshalError is the error returned by the Message's UnmarshalText method. If the error is related to a specific field, FieldName will be a non-empty string. If no fields were found in the target text or any other errors occurred, only a Reason will be provided. Reason is always present.
func (*UnmarshalError) Error ¶
func (u *UnmarshalError) Error() string
func (*UnmarshalError) Unwrap ¶
func (u *UnmarshalError) Unwrap() error
type UpgradedRequest ¶
type UpgradedRequest struct {
// contains filtered or unexported fields
}
An UpgradedRequest is used to send events to the client. Create one using the Upgrade function.
func Upgrade ¶
func Upgrade(w http.ResponseWriter) (UpgradedRequest, error)
Upgrade upgrades an HTTP request to support server-sent events. It returns a Connection that's used to send events to the client or an error if the upgrade failed.
The headers required by the SSE protocol are only sent when calling the Send method for the first time. If other operations are done before sending messages, other headers and status codes can safely be set.
func (*UpgradedRequest) Send ¶
func (u *UpgradedRequest) Send(e *Message) error
Send sends the given event to the client. It returns any errors that occurred while writing the event.
type ValidReplayProvider ¶
type ValidReplayProvider struct {
// contains filtered or unexported fields
}
ValidReplayProvider is a replay provider that replays all the valid (not expired) previous events.
func NewValidReplayProvider ¶
func NewValidReplayProvider(autoIDs ...bool) *ValidReplayProvider
NewValidReplayProvider creates a replay Provider that replays all the buffered non-expired events. Call its GC method periodically to remove expired events from the buffer and release resources. You can use this provider for replaying an infinite number of events, if the events never expire. The events must have an ID unless the provider is constructed with autoIDs flag as true.
func (*ValidReplayProvider) GC ¶
func (v *ValidReplayProvider) GC() error
GC removes all the expired messages from the provider's buffer.
func (*ValidReplayProvider) Put ¶
func (v *ValidReplayProvider) Put(message **Message)
Put puts the message into the provider's buffer.
func (*ValidReplayProvider) Replay ¶
func (v *ValidReplayProvider) Replay(subscription Subscription) bool
Replay replays all the valid messages to the listener.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
complex
command
|
|
|
complex_client
command
|
|
|
helloworld
command
|
|
|
helloworld_client
command
|
|
|
internal
|
|