Skip to content

Upgraders and dialers

Gerasimos (Makis) Maropoulos edited this page Jun 28, 2019 · 2 revisions

Neffos should run behind a low-level websocket implementation for Go. The developer has full control of this, to use her/his own or wrap an existing one. Neffos comes with two built-in low-level websocket implementations for Upgrading incoming http connections or Dialing the websocket server through Go (note that neffos provides clients for Nodejs & Browser too, see the neffos.js project to learn about). Those two optional dependencies are downloaded automatically for you on the Installation process.

  1. github.com/gorilla/websocket
    • When server wants to Upgrade using gorilla/websocket.Upgrader or when a client wants to dial using the gorilla/websocket.Dialer.
  2. github.com/gobwas/ws
    • When server wants to Upgrade using gobwas/ws.HTTPUpgrader or when a client wants to dial using the gobwas/ws.Dialer.

Neffos provides an easy way to adapt those through the following sub-packages:

  1. github.com/kataras/neffos/gorilla
    • DefaultUpgrader
    • Upgrader(websocket.Upgrader) neffos.Upgrader
    • DefaultDialer
    • Dialer(dialer *websocket.Dialer, requestHeader http.Header) neffos.Dialer
  2. github.com/kataras/neffos/gobwas
    • DefaultUpgrader
    • Upgrader(upgrader ws.HTTPUpgrader) neffos.Upgrader
    • DefaultDialer
    • Dialer(dialer ws.Dialer) neffos.Dialer

However, it is possible to wrap an existing one or implement your own and pass it to a neffos server and/or neffos client.

The neffos.New accepts a neffos.Upgrader.

type Upgrader func(w http.ResponseWriter, r *http.Request) (Socket, error)

The neffos.Dial accepts a neffos.Dialer.

type Dialer func(ctx context.Context, url string) (Socket, error)

Both Upgrader and Dialer should return a valid neffos.Socket.

Socket interface {
    // NetConn returns the underline net connection.
    NetConn() net.Conn
    // Request returns the http request value.
    Request() *http.Request
    // ReadData reads binary or text messages from the remote connection.
    ReadData(timeout time.Duration) (body []byte, err error)
    // WriteBinary sends a binary message to the remote connection.
    WriteBinary(body []byte, timeout time.Duration) error
    // WriteText sends a text message to the remote connection.
    WriteText(body []byte, timeout time.Duration) error
}

Usage

package server

import (
    "github.com/kataras/neffos"
    "github.com/kataras/neffos/gorilla"
)

func main() {
    server := neffos.New(gorilla.DefaultUpgrader, events)
    // [...]
}
package client

import (
    "context"

    "github.com/kataras/neffos"
    "github.com/kataras/neffos/gorilla"
)

func main() {
    client, err := neffos.Dial(context.Background(), gorilla.DefaultDialer, events)
    // [...]
}