Encoding

With neffos you can send any type of data, remember? The neffos.Message.Body field is just a []byte. At short, the neffos.Message.Body is the raw data client/server sends, users of the neffos package can use any format to unmarshal on read and marshal to send, such as protocol-buffers, encoding/json, encoding/xml and etc.

In this section you will learn how to send JSON data to Rooms using the Emit with neffos.Marshal and how to read those data inside an event callback's with the neffos.Message.Unmarshal method. The neffos.DefaultMarshaler/Unnmarshaler will be used on neffos.Marshal and neffos.Message.Unmarshal if the value you are trying to send/read does not complete the neffos.MessageObjectMarshaler on send and neffos.MessageObjectUnmarshaler on read, therefore the default encoding that neffos using for struct values is the JSON one. Below you will find a brief outline of the above:

package neffos

var (
    DefaultMarshaler = json.Marshal
    DefaultUnmarshaler = json.Unmarshal
)

type (
    MessageObjectMarshaler interface {
        Marshal() ([]byte, error)
    }

    MessageObjectUnmarshaler interface {
        Unmarshal(body []byte) error
    }
)

type Message struct {
    // [...]
}

func (m *Message) Unmarshal(outPtr interface{}) error {
    if unmarshaler, ok := outPtr.(MessageObjectUnmarshaler); ok {
        return unmarshaler.Unmarshal(m.Body)
    }

    return DefaultUnmarshaler(m.Body, outPtr)
}

Create our userMessage structure

Define the server and client events

Create and run our Server

Create our (Go) Client side

Create our (Javascript browserify) Client side

In this example, we make an exception and we include the browser-side as well, so you can have a small taste of it.

Read more about neffos.js.

Third-party Requirements

How to run

Open a terminal window instance and execute:

Open some web browser windows and navigate to http://localhost:8080, each window will ask for a username and a room to join, each window(client connection) and server get notified for namespace connected/disconnected, room joined/left and chat events.

To start the go client side just open a new terminal window and execute:

It will ask you for username and a room to join as well, it acts exactly the same as the ./browser/app.js browser-side application.

Read the full source code of this example by navigating to the repository's _examples/basic directory.

You can continue by learning how to send and receive Protobufs.

Last updated