Skip to content

kataras/go-websocket

Repository files navigation

Build Status License Releases Read me docs Build Status Built with GoLang Platforms

The package go-websocket provides an easy way to setup a rich Websocket server and client side.

It's already tested on production & used on Iris.

Installation

The only requirement is the Go Programming Language.

$ go get -u github.com/kataras/go-websocket

Examples

To view working examples please navigate to the ./examples folder.

Docs

WebSocket is a protocol providing full-duplex communication channels over a single TCP connection. The WebSocket protocol was standardized by the IETF as RFC 6455 in 2011, and the WebSocket API in Web IDL is being standardized by the W3C.

WebSocket is designed to be implemented in web browsers and web servers, but it can be used by any client or server application. The WebSocket protocol is an independent TCP-based protocol. Its only relationship to HTTP is that its handshake is interpreted by HTTP servers as an Upgrade request. The WebSocket protocol makes more interaction between a browser and a website possible, facilitating real-time data transfer from and to the server.

Read more about Websockets on Wikipedia.


Configuration

// Config the websocket server configuration
type Config struct {
    // IDGenerator used to create (and later on, set)
    // an ID for each incoming websocket connections (clients).
    // The request is an input parameter which you can use to generate the ID (from headers for example).
    // If empty then the ID is generated by DefaultIDGenerator: uuid or,if failed, a randomString(64)
    IDGenerator func(w http.ResponseWriter, r *http.Request) string
    // EvtMessagePrefix is the prefix of the underline websocket events that are being established under the hoods.
    // This prefix is visible only to the javascript side (code) and it has nothing to do
    // with the message that the end-user receives.
    // Do not change it unless it is absolutely necessary.
    //
    // If empty then defaults to []byte("go-websocket-message:").
    EvtMessagePrefix []byte
    // Error is the function that will be fired if any client couldn't upgrade the HTTP connection
    // to a websocket connection, a handshake error.
    Error func(w http.ResponseWriter, r *http.Request, status int, reason error)
    // CheckOrigin a function that is called right before the handshake,
    // if returns false then that client is not allowed to connect with the websocket server.
    CheckOrigin func(r *http.Request) bool
    // HandshakeTimeout specifies the duration for the handshake to complete.
    HandshakeTimeout time.Duration
    // WriteTimeout time allowed to write a message to the connection.
    // 0 means no timeout.
    // Default value is 0
    WriteTimeout time.Duration
    // ReadTimeout time allowed to read a message from the connection.
    // 0 means no timeout.
    // Default value is 0
    ReadTimeout time.Duration
    // PongTimeout allowed to read the next pong message from the connection.
    // Default value is 60 * time.Second
    PongTimeout time.Duration
    // PingPeriod send ping messages to the connection within this period. Must be less than PongTimeout.
    // Default value is 60 *time.Second
    PingPeriod time.Duration
    // MaxMessageSize max message size allowed from connection.
    // Default value is 1024
    MaxMessageSize int64
    // BinaryMessages set it to true in order to denotes binary data messages instead of utf-8 text
    // compatible if you wanna use the Connection's EmitMessage to send a custom binary data to the client, like a native server-client communication.
    // Default value is false
    BinaryMessages bool
    // ReadBufferSize is the buffer size for the connection reader.
    // Default value is 4096
    ReadBufferSize int
    // WriteBufferSize is the buffer size for the connection writer.
    // Default value is 4096
    WriteBufferSize int
    // EnableCompression specify if the server should attempt to negotiate per
    // message compression (RFC 7692). Setting this value to true does not
    // guarantee that compression will be supported. Currently only "no context
    // takeover" modes are supported.
    //
    // Defaults to false and it should be remain as it is, unless special requirements.
    EnableCompression bool

    // Subprotocols specifies the server's supported protocols in order of
    // preference. If this field is set, then the Upgrade method negotiates a
    // subprotocol by selecting the first match in this list with a protocol
    // requested by the client.
    Subprotocols []string
}

OUTLINE

// ws := websocket.New(websocket.Config...{})
// ws.websocket.OnConnection(func(c websocket.Connection){})
// or package-default
websocket.OnConnection(func(c websocket.Connection){})

Connection's methods

ID() string

Request() *http.Request

// Receive from the client
On("anyCustomEvent", func(message string) {})
On("anyCustomEvent", func(message int){})
On("anyCustomEvent", func(message bool){})
On("anyCustomEvent", func(message anyCustomType){})
On("anyCustomEvent", func(){})

// Receive a native websocket message from the client
// compatible without need of import the go-websocket.js to the .html
OnMessage(func(message []byte){})

// Send to the client
Emit("anyCustomEvent", string)
Emit("anyCustomEvent", int)
Emit("anyCustomEvent", bool)
Emit("anyCustomEvent", anyCustomType)

// Send native websocket messages
// with config.BinaryMessages = true
// useful when you use proto or something like this.
//
// compatible without need of import the go-websocket.js to the .html
EmitMessage([]byte("anyMessage"))

// Send to specific client(s)
To("otherConnectionId").Emit/EmitMessage...
To("anyCustomRoom").Emit/EmitMessage...

// Send to all opened connections/clients
To(websocket.All).Emit/EmitMessage...

// Send to all opened connections/clients EXCEPT this client
To(websocket.Broadcast).Emit/EmitMessage...

// Rooms, group of connections/clients
Join("anyCustomRoom")
Leave("anyCustomRoom")


// Fired when the connection is closed
OnDisconnect(func(){})

// Force-disconnect the client from the server-side
Disconnect() error

FAQ

Explore these questions or navigate to the community chat.

Versioning

Current: v0.1.0

People

The author of go-websocket is @kataras.

If you're willing to donate, feel free to send any amount through paypal

Contributing

If you are interested in contributing to the go-websocket project, please make a PR.

License

This project is licensed under the MIT License.

License can be found here.