websocket - ActiveState ActiveGo 1.8

Package websocket

import "golang.org/x/net/websocket"

Overview ▾

Package websocket implements a client and server for the WebSocket protocol as specified in RFC 6455.

This package currently lacks some features found in an alternative and more actively maintained WebSocket package:


Index ▾



Package files

client.go dial.go hybi.go server.go websocket.go


const (
    ProtocolVersionHybi13    = 13
    ProtocolVersionHybi      = ProtocolVersionHybi13
    SupportedProtocolVersion = "13"

    ContinuationFrame = 0
    TextFrame         = 1
    BinaryFrame       = 2
    CloseFrame        = 8
    PingFrame         = 9
    PongFrame         = 10
    UnknownFrame      = 255

    DefaultMaxPayloadBytes = 32 << 20 // 32MB


var (
    ErrBadMaskingKey         = &ProtocolError{"bad masking key"}
    ErrBadPongMessage        = &ProtocolError{"bad pong message"}
    ErrBadClosingStatus      = &ProtocolError{"bad closing status"}
    ErrUnsupportedExtensions = &ProtocolError{"unsupported extensions"}
    ErrNotImplemented        = &ProtocolError{"not implemented"}
var (
    ErrBadProtocolVersion   = &ProtocolError{"bad protocol version"}
    ErrBadScheme            = &ProtocolError{"bad scheme"}
    ErrBadStatus            = &ProtocolError{"bad status"}
    ErrBadUpgrade           = &ProtocolError{"missing or bad upgrade"}
    ErrBadWebSocketOrigin   = &ProtocolError{"missing or bad WebSocket-Origin"}
    ErrBadWebSocketLocation = &ProtocolError{"missing or bad WebSocket-Location"}
    ErrBadWebSocketProtocol = &ProtocolError{"missing or bad WebSocket-Protocol"}
    ErrBadWebSocketVersion  = &ProtocolError{"missing or bad WebSocket Version"}
    ErrChallengeResponse    = &ProtocolError{"mismatch challenge/response"}
    ErrBadFrame             = &ProtocolError{"bad frame"}
    ErrBadFrameBoundary     = &ProtocolError{"not on frame boundary"}
    ErrNotWebSocket         = &ProtocolError{"not websocket protocol"}
    ErrBadRequestMethod     = &ProtocolError{"bad method"}
    ErrNotSupported         = &ProtocolError{"not supported"}

ErrFrameTooLarge is returned by Codec's Receive method if payload size exceeds limit set by Conn.MaxPayloadBytes

var ErrFrameTooLarge = errors.New("websocket: frame payload size exceeds limit")

JSON is a codec to send/receive JSON data in a frame from a WebSocket connection.

Trivial usage:

import "websocket"

type T struct {
	Msg string
	Count int

// receive JSON type T
var data T
websocket.JSON.Receive(ws, &data)

// send JSON type T
websocket.JSON.Send(ws, data)
var JSON = Codec{jsonMarshal, jsonUnmarshal}

Message is a codec to send/receive text/binary data in a frame on WebSocket connection. To send/receive text frame, use string type. To send/receive binary frame, use []byte type.

Trivial usage:

import "websocket"

// receive text frame
var message string
websocket.Message.Receive(ws, &message)

// send text frame
message = "hello"
websocket.Message.Send(ws, message)

// receive binary frame
var data []byte
websocket.Message.Receive(ws, &data)

// send binary frame
data = []byte{0, 1, 2}
websocket.Message.Send(ws, data)
var Message = Codec{marshal, unmarshal}

func Origin

func Origin(config *Config, req *http.Request) (*url.URL, error)

Origin parses the Origin header in req. If the Origin header is not set, it returns nil and nil.

type Addr

Addr is an implementation of net.Addr for WebSocket.

type Addr struct {

func (*Addr) Network

func (addr *Addr) Network() string

Network returns the network type for a WebSocket, "websocket".

type Codec

Codec represents a symmetric pair of functions that implement a codec.

type Codec struct {
    Marshal   func(v interface{}) (data []byte, payloadType byte, err error)
    Unmarshal func(data []byte, payloadType byte, v interface{}) (err error)

func (Codec) Receive

func (cd Codec) Receive(ws *Conn, v interface{}) (err error)

Receive receives single frame from ws, unmarshaled by cd.Unmarshal and stores in v. The whole frame payload is read to an in-memory buffer; max size of payload is defined by ws.MaxPayloadBytes. If frame payload size exceeds limit, ErrFrameTooLarge is returned; in this case frame is not read off wire completely. The next call to Receive would read and discard leftover data of previous oversized frame before processing next frame.

func (Codec) Send

func (cd Codec) Send(ws *Conn, v interface{}) (err error)

Send sends v marshaled by cd.Marshal as single frame to ws.

type Config

Config is a WebSocket configuration

type Config struct {
    // A WebSocket server address.
    Location *url.URL

    // A Websocket client origin.
    Origin *url.URL

    // WebSocket subprotocols.
    Protocol []string

    // WebSocket protocol version.
    Version int

    // TLS config for secure WebSocket (wss).
    TlsConfig *tls.Config

    // Additional header fields to be sent in WebSocket opening handshake.
    Header http.Header

    // Dialer used when opening websocket connections.
    Dialer *net.Dialer
    // contains filtered or unexported fields

func NewConfig

func NewConfig(server, origin string) (config *Config, err error)

NewConfig creates a new WebSocket config for client connection.

type Conn

Conn represents a WebSocket connection.

Multiple goroutines may invoke methods on a Conn simultaneously.

type Conn struct {
    PayloadType byte

    // MaxPayloadBytes limits the size of frame payload received over Conn
    // by Codec's Receive method. If zero, DefaultMaxPayloadBytes is used.
    MaxPayloadBytes int
    // contains filtered or unexported fields

func Dial

func Dial(url_, protocol, origin string) (ws *Conn, err error)

Dial opens a new client connection to a WebSocket.


This example demonstrates a trivial client.


origin := "http://localhost/"
url := "ws://localhost:12345/ws"
ws, err := websocket.Dial(url, "", origin)
if err != nil {
if _, err := ws.Write([]byte("hello, world!\n")); err != nil {
var msg = make([]byte, 512)
var n int
if n, err = ws.Read(msg); err != nil {
fmt.Printf("Received: %s.\n", msg[:n])

func DialConfig

func DialConfig(config *Config) (ws *Conn, err error)

DialConfig opens a new client connection to a WebSocket with a config.

func NewClient

func NewClient(config *Config, rwc io.ReadWriteCloser) (ws *Conn, err error)

NewClient creates a new WebSocket client connection over rwc.

func (*Conn) Close

func (ws *Conn) Close() error

Close implements the io.Closer interface.

func (*Conn) Config

func (ws *Conn) Config() *Config

Config returns the WebSocket config.

func (*Conn) IsClientConn

func (ws *Conn) IsClientConn() bool

func (*Conn) IsServerConn

func (ws *Conn) IsServerConn() bool

func (*Conn) LocalAddr

func (ws *Conn) LocalAddr() net.Addr

LocalAddr returns the WebSocket Origin for the connection for client, or the WebSocket location for server.

func (*Conn) Read

func (ws *Conn) Read(msg []byte) (n int, err error)

Read implements the io.Reader interface: it reads data of a frame from the WebSocket connection. if msg is not large enough for the frame data, it fills the msg and next Read will read the rest of the frame data. it reads Text frame or Binary frame.

func (*Conn) RemoteAddr

func (ws *Conn) RemoteAddr() net.Addr

RemoteAddr returns the WebSocket location for the connection for client, or the Websocket Origin for server.

func (*Conn) Request

func (ws *Conn) Request() *http.Request

Request returns the http request upgraded to the WebSocket. It is nil for client side.

func (*Conn) SetDeadline

func (ws *Conn) SetDeadline(t time.Time) error

SetDeadline sets the connection's network read & write deadlines.

func (*Conn) SetReadDeadline

func (ws *Conn) SetReadDeadline(t time.Time) error

SetReadDeadline sets the connection's network read deadline.

func (*Conn) SetWriteDeadline

func (ws *Conn) SetWriteDeadline(t time.Time) error

SetWriteDeadline sets the connection's network write deadline.

func (*Conn) Write

func (ws *Conn) Write(msg []byte) (n int, err error)

Write implements the io.Writer interface: it writes data as a frame to the WebSocket connection.

type DialError

DialError is an error that occurs while dialling a websocket server.

type DialError struct {
    Err error

func (*DialError) Error

func (e *DialError) Error() string

type Handler

Handler is a simple interface to a WebSocket browser client. It checks if Origin header is valid URL by default. You might want to verify websocket.Conn.Config().Origin in the func. If you use Server instead of Handler, you could call websocket.Origin and check the origin in your Handshake func. So, if you want to accept non-browser clients, which do not send an Origin header, set a Server.Handshake that does not check the origin.

type Handler func(*Conn)


This example demonstrates a trivial echo server.


package websocket_test

import (


// Echo the data received on the WebSocket.
func EchoServer(ws *websocket.Conn) {
    io.Copy(ws, ws)

// This example demonstrates a trivial echo server.
func ExampleHandler() {
    http.Handle("/echo", websocket.Handler(EchoServer))
    err := http.ListenAndServe(":12345", nil)
    if err != nil {
        panic("ListenAndServe: " + err.Error())

func (Handler) ServeHTTP

func (h Handler) ServeHTTP(w http.ResponseWriter, req *http.Request)

ServeHTTP implements the http.Handler interface for a WebSocket

type ProtocolError

ProtocolError represents WebSocket protocol errors.

type ProtocolError struct {
    ErrorString string

func (*ProtocolError) Error

func (err *ProtocolError) Error() string

type Server

Server represents a server of a WebSocket.

type Server struct {
    // Config is a WebSocket configuration for new WebSocket connection.

    // Handshake is an optional function in WebSocket handshake.
    // For example, you can check, or don't check Origin header.
    // Another example, you can select config.Protocol.
    Handshake func(*Config, *http.Request) error

    // Handler handles a WebSocket connection.

func (Server) ServeHTTP

func (s Server) ServeHTTP(w http.ResponseWriter, req *http.Request)

ServeHTTP implements the http.Handler interface for a WebSocket