summaryrefslogtreecommitdiff
path: root/test/Program.cs
blob: c5d0ee5bb3d9232fdc529343b9ddf33efe6c75c0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
using System.Net;
using System.Text;

class Program
{
    static void Main(string[] args)
    {
        HttpListener listener = new HttpListener();
        listener.Prefixes.Add("http://localhost:8080/");
        listener.Start();
        Console.WriteLine("HTTP server is running on http://localhost:8080/");
        Console.WriteLine("Press Ctrl+C to stop the server.");

        while (true)
        {
            HttpListenerContext context = listener.GetContext();
            ThreadPool.QueueUserWorkItem(o => HandleRequest(context));
        }
    }

    static void HandleRequest(HttpListenerContext context)
    {
        HttpListenerRequest request = context.Request;
        HttpListenerResponse response = context.Response;

        Console.WriteLine($"Received {request.HttpMethod} request for {request.Url}");

        if (request.HttpMethod == "TRACE")
        {
            HandleTraceMethod(request, response);
        }
        else
        {
            response.StatusCode = (int)HttpStatusCode.MethodNotAllowed;
            using (StreamWriter writer = new StreamWriter(response.OutputStream))
            {
                writer.WriteLine("Method Not Allowed");
            }
        }

        response.Close();
    }

    static void HandleTraceMethod(HttpListenerRequest request, HttpListenerResponse response)
    {
        response.StatusCode = (int)HttpStatusCode.OK;
        response.ContentType = "message/http";

        using (StreamWriter writer = new StreamWriter(response.OutputStream, Encoding.UTF8))
        {
            writer.WriteLine($"{request.HttpMethod} {request.Url} HTTP/{request.ProtocolVersion}");
            foreach (string? header in request.Headers.AllKeys)
            {
                if (header == null)
                {
                    continue;
                }

                writer.WriteLine($"{header}: {request.Headers[header]}");
            }
            writer.WriteLine();
        }
    }
}