Cysharp / MagicOnion

Unified Realtime/API framework for .NET platform and Unity.
MIT License
3.8k stars 424 forks source link

Introduce ServiceContext.SetRawBytesResponse #677

Closed mayuki closed 1 year ago

mayuki commented 1 year ago

This PR introduces ServiceContext.SetRawBytesResponse method.

This method allows you to set raw byte sequences as a response. This makes it possible to send a cached response body without serialization.

public override async ValueTask Invoke(ServiceContext context, Func<ServiceContext, ValueTask> next)
{
    if (ResponseBytesCache.TryGetValue(context.CallContext.Method, out var cachedBytes))
    {
        context.SetRawBytesResponse(cachedBytes);
        return;
    }

    await next(context);

    ResponseBytesCache[context.CallContext.Method] = MessagePackSerializer.Serialize(context.Result);
}

[!NOTE] The raw byte sequence must be serialized as a MessagePack (or custom serialization) format. MagicOnion will write a byte requence directly into the response buffer.