Program.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. using System.IO.Pipelines;
  2. using System.Text.Json;
  3. using System.Text.Json.Serialization;
  4. using Wired.IO.App;
  5. namespace Fullstack;
  6. internal class Program
  7. {
  8. public static async Task Main(string[] args)
  9. {
  10. var expressBuilder = WiredApp.CreateExpressBuilder();
  11. await expressBuilder
  12. .Port(8080)
  13. .NoScopedEndpoints()
  14. .MapGet("/json", _ => async ctx =>
  15. {
  16. var payload = new JsonMessage { Message = JsonBody };
  17. var myHandler = CreateBoundHandler(ctx.Writer, payload);
  18. ctx
  19. .Respond()
  20. .Type("application/json"u8)
  21. .Content(myHandler, 27);
  22. })
  23. .MapGet("/plaintext", _ => async ctx =>
  24. {
  25. ctx
  26. .Respond()
  27. .Type("text/plain"u8)
  28. .Content(_plainTextBody);
  29. })
  30. .Build()
  31. .RunAsync();
  32. }
  33. private static ReadOnlySpan<byte> _plainTextBody => "Hello, World!"u8;
  34. private const string JsonBody = "Hello, World!";
  35. [ThreadStatic]
  36. private static Utf8JsonWriter? t_writer;
  37. private static readonly Action<PipeWriter, JsonMessage> StaticHandler = HandleFast;
  38. private static Action CreateBoundHandler(PipeWriter writer, JsonMessage message) => () => StaticHandler.Invoke(writer, message);
  39. private static void HandleFast(PipeWriter writer, JsonMessage message)
  40. {
  41. var utf8JsonWriter = t_writer ??= new Utf8JsonWriter(writer, new JsonWriterOptions { SkipValidation = true });
  42. utf8JsonWriter.Reset(writer);
  43. JsonSerializer.Serialize(utf8JsonWriter, message, SerializerContext.JsonMessage);
  44. }
  45. private static readonly JsonContext SerializerContext = JsonContext.Default;
  46. }
  47. public struct JsonMessage { public string Message { get; set; } }
  48. [JsonSourceGenerationOptions(GenerationMode = JsonSourceGenerationMode.Serialization | JsonSourceGenerationMode.Metadata)]
  49. [JsonSerializable(typeof(JsonMessage))]
  50. public partial class JsonContext : JsonSerializerContext { }