Program.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. using System;
  2. using System.Linq;
  3. using System.Net;
  4. using System.Text.Json;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. using WatsonWebserver;
  8. namespace Benchmarks
  9. {
  10. #region Supporting data structures
  11. public class JsonResult
  12. {
  13. public string Message { get; set; }
  14. }
  15. #endregion
  16. public static class Program
  17. {
  18. private static readonly ManualResetEvent _WaitEvent = new ManualResetEvent(false);
  19. public static async Task<int> Main(string[] args)
  20. {
  21. #if DEBUG
  22. var host = "127.0.0.1";
  23. #else
  24. var host = "tfb-server";
  25. #endif
  26. using var server = new Server(host, 8080, false, DefaultRoute);
  27. server.Routes.Static.Add(HttpMethod.GET, "/plaintext", PlaintextRoute);
  28. server.Routes.Static.Add(HttpMethod.GET, "/json", JsonRoute);
  29. try
  30. {
  31. AppDomain.CurrentDomain.ProcessExit += (_, __) =>
  32. {
  33. _WaitEvent.Set();
  34. };
  35. await server.StartAsync();
  36. _WaitEvent.WaitOne();
  37. return 0;
  38. }
  39. catch (Exception e)
  40. {
  41. Console.WriteLine(e);
  42. return -1;
  43. }
  44. }
  45. static async Task DefaultRoute(HttpContext ctx)
  46. {
  47. ctx.Response.StatusCode = 404;
  48. ctx.Response.StatusDescription = "Not Found";
  49. await ctx.Response.Send("Not found.");
  50. }
  51. static async Task PlaintextRoute(HttpContext ctx)
  52. {
  53. ctx.Response.Headers.Add("Content-Type", "text/plain; charset=UTF-8");
  54. await ctx.Response.Send("Hello, World!");
  55. }
  56. static async Task JsonRoute(HttpContext ctx)
  57. {
  58. var response = new JsonResult() { Message = "Hello, World!" };
  59. var serialized = JsonSerializer.Serialize(response);
  60. ctx.Response.Headers.Add("Content-Type", "application/json; charset=UTF-8");
  61. await ctx.Response.Send(serialized);
  62. }
  63. }
  64. }