-
Notifications
You must be signed in to change notification settings - Fork 22
On function
This is an overview about the capability and information on intrinsics of the On-functionality. For simple tutorials on how to use it follow the tutorial series.
The On-function is in several ways the heart of the golem framework. It is used to catch events emitted from the client on the server-side or the other way around and allows flexible interaction with the transmitted data. To achieve this reflection is used to determine the most efficient way to handle the incoming event and data.
The most lightweight case is an emitted event without data, e.g. client emitting event (i.e. conn.emit("eventwithoutdata");
) and the server wouldn't accept any second argument and therefore incoming bytes will be ignored and just the function is being called (i.e. myrouter.On("eventwithoutdata", func(conn *golem.Connection) {})
). Since no parsing of data is necessary if no data is necessary this should be the desired approach to handle an event.
As already discussed on the protocol-page the inbuilt data format is JSON. Therefore the On-function uses reflection on the server-side to construct a pre-handler that unmarshals the incoming data into the type of the second argument. This means all tags described by the encoding/json-package still work. The usage of tags is helpful since the client-side interacts with the data as well and it is common for JSON-Objects to have lower-case names. An advance usage of tags would be to save bandwidth by choosing short JSON-names.
Another lightweight approach is to directly accept the interstage product. A function accepting this accepts an interface{}. The interstage product is the left over data after unpacking / extracting the event data from it. Since the interstage data is always the same type for an active protocol type assertion based on the active protocol is safe (hence []bytes
for JSON-Protocol, see example_data.go).
If a custom parser is known it will be used to unmarshal the data into the necessary type. More infomation on this mechanism can be found here.