GoWebsocket

repository·master·Indexed 41 days ago

https://github.com/sacoo7/gowebsocket

A simplified WebSocket client implementation for Go built on the Gorilla WebSocket library. It provides abstractions for event-driven communication, handling text and binary data, compression, proxies, and custom request headers via ConnectionOptions.

Tokens
2.5K
Snippets
12
Records
12
Agent score
1%

What's inside GoWebsocket

  1. Initialize and connect a GoWebsocket client

    master

    Create a new client instance using gowebsocket.New(url) and then call socket.Connect() to initiate the handshake. The URL must use either the ws or wss scheme.

    // Create a client instance
    socket := gowebsocket.New("ws://echo.websocket.org/")
    
    // This will send websocket handshake request
    socket.Connect()
  2. Configure ConnectionOptions (SSL, Compression, and Subprotocols)

    master

    Advanced connection settings such as SSL usage, data compression, and subprotocols are configured via the ConnectionOptions struct. Note: These options must be applied to the socket instance before calling Connect().

    socket.ConnectionOptions = gowebsocket.ConnectionOptions {
        UseSSL: true,
        UseCompression: true,
        Subprotocols: []string{"chat", "superchat"},
    }
  3. Send text and binary messages

    master

    Use SendText(string) to transmit text data and SendBinary([]byte) to transmit raw byte slices.

    // Sending Text message
    socket.SendText("Hi there, this is my sample test message")
    
    // Sending Binary data
    token := make([]byte, 4)
    socket.SendBinary(token)
  4. Configure Proxy and Request Headers

    master

    You can customize the connection by setting request headers directly on socket.RequestHeader or by configuring a proxy server via ConnectionOptions using the BuildProxy helper.

    // Setting request headers
    socket.RequestHeader.Set("Accept-Encoding", "gzip, deflate, sdch")
    socket.RequestHeader.Set("User-Agent", "Mozilla/5.0 ...")
    
    // Setting proxy server
    socket.ConnectionOptions = gowebsocket.ConnectionOptions {
       Proxy: gowebsocket.BuildProxy("http://example.com"),
    }
  5. Register event listeners for WebSocket events

    master

    GoWebsocket uses callback functions assigned to specific fields on the Websocket instance to handle lifecycle and data events. You must register these listeners before calling Connect().

    Available event handlers:

    • OnConnected: Triggered when the connection is established.
    • OnConnectError: Triggered if the connection attempt fails.
    • OnTextMessage: Triggered when a text message is received.
    • OnBinaryMessage: Triggered when binary data is received.
    • OnPingReceived: Triggered when a ping is received.
    • OnPongReceived: Triggered when a pong is received.
    • OnDisconnected: Triggered when the connection is closed.
    package main
    
    import (
        "log"
        "github.com/sacOO7/gowebsocket"
        "os"
        "os/signal"
    )
    
    func main() {
        interrupt := make(chan os.Signal, 1)
        signal.Notify(interrupt, os.Interrupt)
    
        socket := gowebsocket.New("ws://echo.websocket.org/")
    
        socket.OnConnected = func(socket gowebsocket.Socket) {
            log.Println("Connected to server")
        }
    
        socket.OnConnectError = func(err error, socket gowebsocket.Socket) {
            log.Println("Received connect error ", err)
        }
    
        socket.OnTextMessage = func(message string, socket gowebsocket.Socket) {
            log.Println("Received message " + message)
        }
    
        socket.OnBinaryMessage = func(data []byte, socket gowebsocket.Socket) {
            log.Println("Received binary data ", data)
        }
    
        socket.OnPingReceived = func(data string, socket gowebsocket.Socket) {
            log.Println("Received ping " + data)
        }
    
        socket.OnPongReceived = func(data string, socket gowebsocket.Socket) {
            log.Println("Received pong " + data)
        }
    
        socket.OnDisconnected = func(err error, socket gowebsocket.Socket) {
            log.Println("Disconnected from server ")
        }
    
        socket.Connect()
    
        for {
            select {
            case <-interrupt:
                log.Println("interrupt")
                socket.Close()
                return
            }
        }
    }
  6. Configure ConnectionOptions

    master

    The ConnectionOptions struct allows you to customize the WebSocket handshake and transport layer:

    • UseCompression (bool): Enables/disables per-message compression.
    • UseSSL (bool): If true, sets InsecureSkipVerify to true in the TLS configuration (useful for self-signed certificates).
    • Proxy (func(*http.Request) (*url.URL, error)): A function to define a custom proxy for the connection.
    • Subprotocols ([]string): A list of subprotocols to include in the handshake.
    socket.ConnectionOptions = gowebsocket.ConnectionOptions{
        UseCompression: true,
        UseSSL:         true,
        Subprotocols:   []string{"chat", "json"},
    }
  7. Handle WebSocket events with callbacks

    master

    The Socket struct provides several callback fields to handle different lifecycle and message events. You should assign these functions before calling Connect().

    Available callbacks:

    • OnConnected(socket Socket): Triggered when the connection is successfully established.
    • OnTextMessage(message string, socket Socket): Triggered when a text message is received.
    • OnBinaryMessage(data []byte, socket Socket): Triggered when a binary message is received.
    • OnConnectError(err error, socket Socket): Triggered if the initial connection fails.
    • OnDisconnected(err error, socket Socket): Triggered when the connection is closed or lost.
    • OnPingReceived(data string, socket Socket): Triggered when a Ping frame is received.
    • OnPongReceived(data string, socket Socket): Triggered when a Pong frame is received.
    socket := gowebsocket.New("ws://example.com/socket")
    
    socket.OnConnected = func(s gowebsocket.Socket) {
        fmt.Println("Connected!")
    }
    
    socket.OnTextMessage = func(msg string, s gowebsocket.Socket) {
        fmt.Printf("Received: %s\n", msg)
    }
    
    socket.OnDisconnected = func(err error, s gowebsocket.Socket) {
        fmt.Printf("Disconnected: %v\n", err)
    }
    
    socket.Connect()
  8. Initialize a new Socket with New()

    master

    Use New(url string) to create a new Socket instance. The returned Socket is pre-configured with default connection options, including SSL enabled by default and no compression. You can further customize the RequestHeader, ConnectionOptions, and Timeout before calling Connect().

    import "github.com/sacoo7/gowebsocket"
    
    socket := gowebsocket.New("ws://example.com/socket")
    socket.ConnectionOptions.UseCompression = true
    socket.Timeout = 30 * time.Second
  9. Connect to a WebSocket server

    master

    Call Connect() on a Socket instance to establish a connection to the specified URL. This method configures the underlying websocket.Dialer using your ConnectionOptions and starts a background goroutine to handle incoming messages.

    Note: Connect() is non-blocking for message receiving, but it performs the initial handshake synchronously.

    socket := gowebsocket.New("ws://example.com/socket")
    socket.Connect()
  10. Enable and manage logging

    master

    By default, logging is set to OFF. You can enable trace-level logging for debugging connection and message events using EnableLogging() or retrieve the logger instance via GetLogger().

    socket.EnableLogging() // Sets level to TRACE