1+ // ReSharper disable always SuggestVarOrType_BuiltInTypes
2+ // (var is avoided intentionally in this project so that concrete types are visible at call sites.)
3+ // ReSharper disable always StackAllocInsideLoop
4+
5+ using System . Runtime . CompilerServices ;
6+ using System . Text . Json ;
7+ using Unhinged ;
8+
9+ #pragma warning disable CA2014
10+
11+ namespace Platform ;
12+
13+ [ SkipLocalsInit ]
14+ internal static class Program
15+ {
16+ public static void Main ( string [ ] args )
17+ {
18+ var builder = UnhingedEngine
19+ . CreateBuilder ( )
20+ . SetNWorkersSolver ( ( ) => Environment . ProcessorCount - 2 ) // Number of working threads, depends on a lot of things
21+ . SetBacklog ( 16384 ) // Accept up to 16384 connections
22+ . SetMaxEventsPerWake ( 512 ) // Max 512 epoll events per wake (quite overkill)
23+ . SetMaxNumberConnectionsPerWorker ( 512 ) // Max 512 connection per thread
24+ . SetPort ( 8080 )
25+ . SetSlabSizes ( 32 * 1024 , 32 * 1024 ) // 32KB slabs to handle high pipeline depth
26+ . InjectRequestHandler ( RequestHandler ) ;
27+
28+ var engine = builder . Build ( ) ;
29+
30+ engine . Run ( ) ;
31+ }
32+
33+ private static void RequestHandler ( Connection connection )
34+ {
35+ // FNV-1a Hashed routes to avoid string allocations
36+ if ( connection . HashedRoute == 291830056 ) // /json
37+ CommitJsonResponse ( connection ) ;
38+
39+ else if ( connection . HashedRoute == 3454831873 ) // /plaintext
40+ CommitPlainTextResponse ( connection ) ;
41+ }
42+
43+ [ ThreadStatic ] private static Utf8JsonWriter ? t_utf8JsonWriter ;
44+ private static readonly JsonContext SerializerContext = JsonContext . Default ;
45+ private static void CommitJsonResponse ( Connection connection )
46+ {
47+ connection . WriteBuffer . WriteUnmanaged ( "HTTP/1.1 200 OK\r \n "u8 +
48+ "Server: W\r \n "u8 +
49+ "Content-Type: application/json; charset=UTF-8\r \n "u8 +
50+ "Content-Length: 27\r \n "u8 ) ;
51+ connection . WriteBuffer . WriteUnmanaged ( DateHelper . HeaderBytes ) ;
52+
53+ t_utf8JsonWriter ??= new Utf8JsonWriter ( connection . WriteBuffer , new JsonWriterOptions { SkipValidation = true } ) ;
54+ t_utf8JsonWriter . Reset ( connection . WriteBuffer ) ;
55+
56+ // Creating(Allocating) a new JsonMessage every request
57+ var message = new JsonMessage { Message = "Hello, World!" } ;
58+ // Serializing it every request
59+ JsonSerializer . Serialize ( t_utf8JsonWriter , message , SerializerContext . JsonMessage ) ;
60+ }
61+
62+ private static void CommitPlainTextResponse ( Connection connection )
63+ {
64+ connection . WriteBuffer . WriteUnmanaged ( "HTTP/1.1 200 OK\r \n "u8 +
65+ "Server: W\r \n "u8 +
66+ "Content-Type: text/plain\r \n "u8 +
67+ "Content-Length: 13\r \n "u8 ) ;
68+ connection . WriteBuffer . WriteUnmanaged ( DateHelper . HeaderBytes ) ;
69+ connection . WriteBuffer . WriteUnmanaged ( "Hello, World!"u8 ) ;
70+ }
71+ }
0 commit comments