1- using System . Net ;
1+ using System . Buffers . Text ;
2+ using System . Net ;
23using System . Text ;
34using System . Text . Json ;
45using Sisk . Cadente ;
56
6- HttpHost . QueueSize = 4096 ;
7-
8- var host = new HttpHost ( new IPEndPoint ( IPAddress . Any , 8080 ) ) ;
9- host . ContextCreated += Host_ContextCreated ;
7+ using var host = new HttpHost ( new IPEndPoint ( IPAddress . Any , 8080 ) ) ;
8+ host . Handler = new DefaultHandler ( ) ;
109
1110host . Start ( ) ;
1211Thread . Sleep ( Timeout . Infinite ) ;
1312
14- void Host_ContextCreated ( HttpHost sender , HttpHostContext session ) {
15- var request = session . Request ;
16-
17- if ( request . Path == "/plaintext" ) {
18- SerializePlainTextResponse ( session . Response ) ;
19- }
20- else if ( request . Path == "/json" ) {
21- SerializeJsonResponse ( session . Response ) ;
22- }
23- else {
24- session . Response . StatusCode = 404 ;
25- }
26- }
27-
28- static void SerializePlainTextResponse ( HttpHostContext . HttpResponse response ) {
29-
30- var messageBytes = Encoding . UTF8 . GetBytes ( "Hello, World!" ) ;
3113
32- response . Headers . Add ( new HttpHeader ( "Content-Type" , "text/plain; charset=UTF-8" ) ) ;
33- response . ResponseStream = new MemoryStream ( messageBytes ) ;
34- }
14+ class DefaultHandler : HttpHostHandler
15+ {
16+ public override async Task OnContextCreatedAsync ( HttpHost host , HttpHostContext context )
17+ {
18+ var request = context . Request ;
19+ var response = context . Response ;
20+
21+ if ( request . Path == "/plaintext" )
22+ {
23+ var contentBytes = Encoding . UTF8 . GetBytes ( "Hello, World!" ) ;
24+
25+ await SerializeResponseAsync ( response , contentBytes , "text/plain; charset=utf-8" ) ;
26+ }
27+ else if ( request . Path == "/json" )
28+ {
29+ var contentBytes = JsonSerializer . SerializeToUtf8Bytes ( new
30+ {
31+ message = "Hello, World!"
32+ } ) ;
33+
34+ await SerializeResponseAsync ( response , contentBytes , "application/json; charset=utf-8" ) ;
35+ }
36+ else
37+ {
38+ response . StatusCode = 404 ;
39+ }
40+ }
3541
36- static void SerializeJsonResponse ( HttpHostContext . HttpResponse response ) {
42+ static async ValueTask SerializeResponseAsync ( HttpHostContext . HttpResponse response , Memory < byte > content , string contentType )
43+ {
44+ response . Headers . Add ( new HttpHeader ( "Content-Type" , contentType ) ) ;
45+ response . Headers . Add ( new HttpHeader ( "Content-Length" , content . Length . ToString ( ) ) ) ;
3746
38- var contentBytes = JsonSerializer . SerializeToUtf8Bytes ( new {
39- message = "Hello, World!"
40- } ) ;
41-
42- response . Headers . Add ( new HttpHeader ( "Content-Type" , "application/json" ) ) ;
43- response . ResponseStream = new MemoryStream ( contentBytes ) ;
47+ using var responseStream = await response . GetResponseStreamAsync ( ) ;
48+ await responseStream . WriteAsync ( content ) ;
49+ }
4450}
0 commit comments