2016-06-20 12:20:37 +00:00
|
|
|
|
using System;
|
|
|
|
|
using System.Collections.Generic;
|
|
|
|
|
using System.Text;
|
2016-06-20 21:22:20 +00:00
|
|
|
|
using Newtonsoft.Json;
|
2016-06-20 12:20:37 +00:00
|
|
|
|
|
2021-11-28 13:18:21 +00:00
|
|
|
|
namespace PettingZoo.Core.Rendering
|
2016-06-20 12:20:37 +00:00
|
|
|
|
{
|
|
|
|
|
public class MessageBodyRenderer
|
|
|
|
|
{
|
2021-12-31 17:48:04 +00:00
|
|
|
|
private static readonly Dictionary<string, Func<byte[], string>> ContentTypeHandlers = new()
|
2016-06-20 12:20:37 +00:00
|
|
|
|
{
|
2016-06-20 21:22:20 +00:00
|
|
|
|
{ "application/json", RenderJson }
|
2016-06-20 12:20:37 +00:00
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
|
2021-12-06 13:08:29 +00:00
|
|
|
|
public static string Render(byte[] body, string? contentType)
|
2016-06-20 12:20:37 +00:00
|
|
|
|
{
|
2021-12-31 17:48:04 +00:00
|
|
|
|
return contentType != null && ContentTypeHandlers.TryGetValue(contentType, out var handler)
|
2021-11-28 13:18:21 +00:00
|
|
|
|
? handler(body)
|
|
|
|
|
: Encoding.UTF8.GetString(body);
|
2016-06-20 21:22:20 +00:00
|
|
|
|
|
|
|
|
|
// ToDo hex output if required
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
public static string RenderJson(byte[] body)
|
|
|
|
|
{
|
|
|
|
|
var bodyText = Encoding.UTF8.GetString(body);
|
|
|
|
|
try
|
2016-06-20 12:20:37 +00:00
|
|
|
|
{
|
2016-06-20 21:22:20 +00:00
|
|
|
|
var obj = JsonConvert.DeserializeObject(bodyText);
|
|
|
|
|
return JsonConvert.SerializeObject(obj, Formatting.Indented);
|
|
|
|
|
}
|
|
|
|
|
catch
|
|
|
|
|
{
|
|
|
|
|
return bodyText;
|
2016-06-20 12:20:37 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|