json.cs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  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 static readonly JsonSerializerOptions SerializerOptions = new JsonSerializerOptions();
  14. private static Utf8JsonWriter GetUtf8JsonWriter(PipeStream stream, HttpToken token)
  15. {
  16. var buffer = stream.CreateBufferWriter();
  17. if (token.Utf8JsonWriter == null)
  18. {
  19. token.Utf8JsonWriter = new Utf8JsonWriter(buffer, new JsonWriterOptions { SkipValidation = true });
  20. }
  21. var writer = token.Utf8JsonWriter;
  22. writer.Reset(buffer);
  23. return writer;
  24. }
  25. public ValueTask Json(PipeStream stream, HttpToken token, ISession session)
  26. {
  27. if (Program.Debug)
  28. {
  29. System.Text.Json.JsonSerializer.Serialize<JsonMessage>(GetUtf8JsonWriter(stream, token), new JsonMessage { message = "Hello, World!" }, SerializerOptions);
  30. }
  31. else
  32. {
  33. SpanJson.JsonSerializer.NonGeneric.Utf8.SerializeAsync(new JsonMessage { message = "Hello, World!" }, stream);
  34. }
  35. OnCompleted(stream, session, token);
  36. return ValueTask.CompletedTask;
  37. }
  38. }
  39. }