Documentation ¶
Overview ¶
Package ws implements common websocket functionality, such as heartbeats and message data streaming.
Event Handlers ¶
You use this packet primarily by specifying an event handler function, which then gets passed a series of events, such as Connected, TextMessage, and Disconnected.
You can access the event's data either by reading it all right into memory using Event.Text() and Event.Data(), or you can stream the event's data by using it as an io.Reader. Note that all the underlying event data must be read during the duration of its EventHandler function invocation.
Servers ¶
See UpgradeRequests() and its example for server usage.
Clients ¶
See Connect() and its example for client usage.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( // WriteWait is the time allowed to write a message to the peer. WriteWait = 10 * time.Second // PongWait is the time allowed to read the next pong message from the peer. PongWait = 60 * time.Second // MaxMessageSize is the maximum message size allowed from peer. MaxMessageSize = int64(512) // ReadBufferSize is the size of websocket upgrader ReadBufferSize = 4096 // WriteBufferSize is the size of websocket upgrader WriteBufferSize = 4096 // HandshakeTimeout specifies the duration for the handshake to complete. HandshakeTimeout = time.Duration(0) // ConnMaxSendBufferLen is the Maximum number of messages to buffer per // connection before SendText and SendBinary starts dropping messages and // return ErrorSendFullBuffer. ConnMaxSendBufferLen = 64 )
var ( // ErrorSendClosedConn is returned by SendText and SendBinary if called // on a closed connection. ErrorSendClosedConn = errors.New("send on closed connection") // ErrorSendFullBuffer is returned by SendText and SendBinary if called // on a connection with a full buffer. ErrorSendFullBuffer = errors.New("send on connection with full buffer") )
var ( // TextMessage signifies that a text message was received. // Use Event.Text() to read the string. TextMessage = EventType(1) // BinaryMessage signifies that a binary frame was received. // Use Event.Data() to read the data. BinaryMessage = EventType(2) // Connected signifies that the websocket connected. // You are online! Connected = EventType(3) // Disconnected signifies that the websocket disconnected. // It should no longer be used. Disconnected = EventType(4) // NetError signifies that a network error occured. // This will always be followed by a Disconnected event. // These events can generally be ignored. NetError = EventType(5) // Error signifies that an unforeseen error occured. // This will always be followed by a Disconnected event. Error = EventType(6) )
var ( // CheckOrigin will be called by the upgrader on incoming requests to check // the origin. If the CheckOrigin function returns false, then the Upgrade // method fails the WebSocket handshake with HTTP status 403. // If nil, then use a safe default: fail the handshake if the Origin request // header is present and not equal to the Host request header. CheckOrigin func(r *http.Request) bool // ErrorFn specifies the function for generating HTTP error responses. // If nil, then http.Error is used to generate the HTTP response. ErrorFn func(w http.ResponseWriter, r *http.Request, status int, reason error) )
Functions ¶
func Connect ¶
func Connect(addr string, eventHandler EventHandler)
Connect opens a websocket connection to the given address, and starts generating events.
Example (Client) ¶
doneChan := make(chan bool) defer func() { <-doneChan }() ws.Connect("http://localhost:8087/ws/echo", func(event *ws.Event, conn *ws.Conn) { switch event.Type { case ws.Connected: fmt.Println("- Connected") conn.SendText("Hello!") case ws.TextMessage: text, _ := event.Text() fmt.Println("- Received", text) conn.SendText("Disconnect me") case ws.Disconnected: fmt.Println("- Disconnected") doneChan <- true } })
Output: - Connected - Received Hello! - Disconnected
func UpgradeHandlerFunc ¶
func UpgradeHandlerFunc(eventHandler EventHandler) http.HandlerFunc
UpgradeHandlerFunc returns a http.HandlerFunc which will upgrade any incoming http websocket upgrade requests to websocket connections matching the given pattern, and then call the event handler function with connection events.
func UpgradeRequests ¶
func UpgradeRequests(pattern string, eventHandler EventHandler)
UpgradeRequests will start upgrading any http requests matching the given pattern. Calling it is equivalent to calling http.HandleFunc(pattern, birect.UpgradeHandlerFunc(eventHandler))
Example (Server) ¶
// Implement an echo server with logging of connection events ws.UpgradeRequests("/ws/echo", func(event *ws.Event, conn *ws.Conn) { switch event.Type { case ws.Connected: fmt.Println("Client connected:", conn.HTTPRequest.RemoteAddr) case ws.TextMessage: text, err := event.Text() fmt.Println("Echo message:", text, err) conn.SendText(text) case ws.BinaryMessage: data, err := event.Data() // or use `event` as an `io.Reader` fmt.Println("Echo binary message of size:", len(data), err) conn.SendBinary(data) case ws.Error: panic("Error! " + event.Error.Error()) case ws.NetError: fmt.Println("Network error:", event.Error) case ws.Disconnected: fmt.Println("Client disconnected:", conn.HTTPRequest.RemoteAddr) } }) // ws.UpgradeRequests requires a listening http server go http.ListenAndServe("localhost:8080", nil)
Output:
Types ¶
type Conn ¶
Conn is a handle to underlying websocket connections. It allows you to send messages and close the connection, as well as to get info on the underlying HTTP Request.
func (*Conn) Close ¶
func (c *Conn) Close()
Close the connection. Once Close has returned no more messages will be sent. However, the connection's EventHandler function may still generate more events.
func (*Conn) SendBinary ¶
SendBinary sends a binary websocket message and returns an error if the connection has been closed (ErrorSendClosedConn) or if its send buffer is full (ErrorSendFullBuffer).
type Event ¶
Event encapsulates the information passed to EventHandlers. Note that Event.Text, Event.Data and Event.Read may only be called during the duriduration of its EventHandler function. As soon as the EventHandler returns, the underlying io.Reader will no longer be valid.
type EventHandler ¶
EventHandler is a function that gets called once for each connection event. Each connection's EventHandler function is guaranteed to be called serially per-connection, but may be called concurrently across multiple connections.