Documentation
¶
Overview ¶
Package events serves connections through a Handler interface instead of a read loop: a thin layer over transport and ws.Serve.
Example ¶
package main
import (
"log"
"net"
"time"
"github.com/33TU/ews/codec"
"github.com/33TU/ews/events"
"github.com/33TU/ews/transport"
"github.com/33TU/ews/ws"
)
// echo is a gws-style handler, one instance shared by every connection. A
// pong from the peer refreshes the deadline set on open: the usual
// keepalive, with pings from one ticker elsewhere. Base answers pings.
type echo struct{ events.Base }
func (echo) OnOpen(c *events.Conn) {
log.Printf("%s connected to %s", c.Request.RemoteAddr, c.Request.Path)
c.SetReadDeadline(time.Now().Add(time.Minute))
}
func (echo) OnMessage(c *events.Conn, op codec.Opcode, payload []byte) error {
return c.Write(op, payload)
}
func (echo) OnPong(c *events.Conn, _ []byte) error {
return c.SetReadDeadline(time.Now().Add(time.Minute))
}
func (echo) OnClose(c *events.Conn, err error) { log.Printf("closed: %v", err) }
func main() {
server := &transport.Server{Handler: events.Serve(echo{}, ws.Config{ValidateUTF8: true})}
ln, _ := net.Listen("tcp", "127.0.0.1:0")
go server.Serve(ln)
server.Close()
}
Output:
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
Types ¶
type Conn ¶
Conn is the connection the events receive: the WebSocket with its deadlines and addresses, the upgrade request, and Value, free for the handler's per-connection state.
type Handler ¶
type Handler interface {
OnOpen(c *Conn)
OnMessage(c *Conn, op codec.Opcode, payload []byte) error
OnPing(c *Conn, payload []byte) error // Must send the pong.
OnPong(c *Conn, payload []byte) error
OnClose(c *Conn, err error)
}
Handler receives a connection's events on its read goroutine. Payloads are borrowed until the call returns; an error ends the connection and is passed to OnClose, as is the *ws.CloseError of a peer's close and, as a *PanicError, a panic in any other event. One Handler serves every connection. Embed Base for the defaults.
type PanicError ¶
PanicError is the error OnClose receives when another event panicked: the connection ends, the process does not. OnClose may re-panic to restore that behavior.
func (*PanicError) Error ¶
func (e *PanicError) Error() string