2016-06-20 12:20:37 +00:00
|
|
|
|
using System;
|
|
|
|
|
using System.Collections.Generic;
|
2022-01-23 10:41:00 +00:00
|
|
|
|
using System.IO;
|
2016-06-20 12:20:37 +00:00
|
|
|
|
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
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
public static string RenderJson(byte[] body)
|
|
|
|
|
{
|
|
|
|
|
var bodyText = Encoding.UTF8.GetString(body);
|
|
|
|
|
try
|
2016-06-20 12:20:37 +00:00
|
|
|
|
{
|
2022-01-23 10:41:00 +00:00
|
|
|
|
using var stringReader = new StringReader(bodyText);
|
|
|
|
|
using var jsonTextReader = new JsonTextReader(stringReader);
|
|
|
|
|
using var stringWriter = new StringWriter();
|
|
|
|
|
using var jsonWriter = new JsonTextWriter(stringWriter);
|
|
|
|
|
|
|
|
|
|
jsonWriter.Formatting = Formatting.Indented;
|
|
|
|
|
|
|
|
|
|
while (jsonTextReader.Read())
|
|
|
|
|
jsonWriter.WriteToken(jsonTextReader);
|
|
|
|
|
|
|
|
|
|
jsonWriter.Flush();
|
|
|
|
|
return stringWriter.ToString();
|
2016-06-20 21:22:20 +00:00
|
|
|
|
}
|
|
|
|
|
catch
|
|
|
|
|
{
|
|
|
|
|
return bodyText;
|
2016-06-20 12:20:37 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|