Using an extended connection type - trevex/golem GitHub Wiki

Golem allows extending the connection type. Only a single connection extension is currently allowed per router (this might change if there is a specific use-case for multiple extensions per router). A connection extension is an extended type of a connection. This allows adding more functionality to the connection. The most common use case are adding of storage or additional methods to the connection.

Enabling an extension is done by calling the SetConnectionExtension of the desired router or SetDefaultConnectionExtension to set the initial extension. The only parameter taken is the constructor of the connection extension.

The best way to extend an connection is to embed its functionality:

type ExtendedConnection struct {
	*golem.Connection
	Counter int
}

In this case we simply added a counter we will increase on every message being sent and a method making answering easier (base of the example is example_simple.go):

func (e *ExtendedConnection) answer(msg string) {
	e.Emit("answer", &Answer{msg})
}

The only requirement for extended connections is that the constructor takes a pointer to a connection as parameter and returns a pointer to the created custom extension:

func NewExtendedConnection(conn *golem.Connection) *ExtendedConnection {
	return &ExtendedConnection{
		Connection: conn,
		Counter:    1,
	}
}

To enable the extended format and be able to use it, the only thing left to do is to set it on the router:

myrouter.SetConnectionExtension(NewExtendedConnection)

Now the previous On-handles of the example_simple.go can be enhanced by using our new type:

func hello(conn *ExtendedConnection, data *Hello) {
	conn.Counter += 1
	fmt.Println("Hello from", data.From, "to", data.To, "Counter:", conn.Counter)
	conn.answer("Thanks, client!")
}
func poke(conn *ExtendedConnection) {
	conn.Counter += 1
	fmt.Println("Poke-Event triggered! Counter:", conn.Counter)
	conn.answer("Ouch I am sensible!")
}

The extended connection constructor is used to create it for every new connection and therefore the it is persistent during connection time. The client (although the same as the example_simple) and server source can be found in the example repository.

Note: Adding storage to the connection would be achieved by adding a map of interfaces to the extended connection.