json.cs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. using BeetleX;
  2. using BeetleX.Buffers;
  3. using SpanJson;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Text;
  7. using System.Text.Json;
  8. using System.Threading.Tasks;
  9. namespace PlatformBenchmarks
  10. {
  11. public partial class HttpHandler
  12. {
  13. private readonly static uint _jsonPayloadSize = (uint)System.Text.Json.JsonSerializer.SerializeToUtf8Bytes(new JsonMessage { message = "Hello, World!" }, SerializerOptions).Length;
  14. private readonly static AsciiString _jsonPreamble =
  15. _headerContentLength + _jsonPayloadSize.ToString();
  16. private static readonly JsonSerializerOptions SerializerOptions = new JsonSerializerOptions();
  17. private static Utf8JsonWriter GetUtf8JsonWriter(PipeStream stream, HttpToken token)
  18. {
  19. var buffer = stream.CreateBufferWriter();
  20. if (token.Utf8JsonWriter == null)
  21. {
  22. token.Utf8JsonWriter = new Utf8JsonWriter(buffer, new JsonWriterOptions { SkipValidation = true });
  23. }
  24. var writer = token.Utf8JsonWriter;
  25. writer.Reset(buffer);
  26. return writer;
  27. }
  28. public ValueTask Json(PipeStream stream, HttpToken token, ISession session)
  29. {
  30. System.Text.Json.JsonSerializer.Serialize<JsonMessage>(GetUtf8JsonWriter(stream, token), new JsonMessage { message = "Hello, World!" }, SerializerOptions);
  31. OnCompleted(stream, session, token);
  32. return ValueTask.CompletedTask;
  33. }
  34. }
  35. }