resultSerializer

UDA for using a custom serializer for the method return value.

Instead of using the default serializer (JSON), this allows to define custom serializers. Multiple serializers can be specified and will be matched against the Accept header of the HTTP request.

alias resultSerializer(alias serialize, alias deserialize, string content_type) = ResultSerializer!(serialize, deserialize, content_type)

Parameters

serialize

An alias to a generic function taking an output range as its first argument and the value to be serialized as its second argument. The result of the serialization is written byte-wise into the output range.

deserialize

An alias to a generic function taking a forward range as its first argument and a reference to the value that is to be deserialized.

content_type

The MIME type of the serialized representation.

Examples

import std.bitmanip : bigEndianToNative, nativeToBigEndian;

interface MyRestInterface {
	static struct Point {
		int x, y;
	}

	static void serialize(R, T)(ref R output_range, const ref T value)
	{
		static assert(is(T == Point)); // only Point supported in this example
		output_range.put(nativeToBigEndian(value.x));
		output_range.put(nativeToBigEndian(value.y));
	}

	static T deserialize(T, R)(R input_range)
	{
		static assert(is(T == Point)); // only Point supported in this example
		T ret;
		ubyte[4] xbuf, ybuf;
		input_range.takeExactly(4).copy(xbuf[]);
		input_range.takeExactly(4).copy(ybuf[]);
		ret.x = bigEndianToNative!int(xbuf);
		ret.y = bigEndianToNative!int(ybuf);
		return ret;
	}

	// serialize as binary data in network byte order
	@resultSerializer!(serialize, deserialize, "application/binary")
	Point getPoint();
}

Meta