Program.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. using EmbedIO;
  2. using Swan.Logging;
  3. using System;
  4. using System.Text;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. namespace Benchmarks
  8. {
  9. #region Supporting data structures
  10. public class JsonResult
  11. {
  12. public string Message { get; set; }
  13. }
  14. #endregion
  15. public static class Program
  16. {
  17. private static readonly ManualResetEvent _WaitEvent = new ManualResetEvent(false);
  18. public static async Task<int> Main(string[] args)
  19. {
  20. Logger.UnregisterLogger<ConsoleLogger>();
  21. using var server = new WebServer(o => o
  22. .WithUrlPrefix("http://+:8080/")
  23. .WithMode(HttpListenerMode.EmbedIO))
  24. .PreferNoCompressionFor("text/*")
  25. .WithAction("/plaintext", HttpVerbs.Get, async (ctx) =>
  26. {
  27. var bytes = Encoding.UTF8.GetBytes("Hello, World!");
  28. ctx.Response.ContentType = "text/plain";
  29. ctx.Response.ContentEncoding = Encoding.UTF8;
  30. ctx.Response.ContentLength64 = bytes.Length;
  31. await ctx.Response.OutputStream.WriteAsync(bytes, 0, bytes.Length);
  32. })
  33. .WithAction("/json", HttpVerbs.Get, async (ctx) =>
  34. {
  35. var data = new JsonResult() { Message = "Hello, World!" };
  36. var serialized = Swan.Formatters.Json.Serialize(data);
  37. var bytes = Encoding.UTF8.GetBytes(serialized);
  38. ctx.Response.ContentType = "application/json";
  39. ctx.Response.ContentEncoding = Encoding.UTF8;
  40. ctx.Response.ContentLength64 = bytes.Length;
  41. await ctx.Response.OutputStream.WriteAsync(bytes, 0, bytes.Length);
  42. });
  43. try
  44. {
  45. AppDomain.CurrentDomain.ProcessExit += (_, __) =>
  46. {
  47. _WaitEvent.Set();
  48. };
  49. await server.RunAsync();
  50. _WaitEvent.WaitOne();
  51. return 0;
  52. }
  53. catch (Exception e)
  54. {
  55. Console.WriteLine(e);
  56. return -1;
  57. }
  58. }
  59. }
  60. }