-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
84 lines (71 loc) · 2.59 KB
/
Program.cs
File metadata and controls
84 lines (71 loc) · 2.59 KB
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
using System;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using languages.HttpModules;
namespace languages
{
class Program
{
const int defaultPort = 8080;
static IHttpModule[] modules = new IHttpModule[] {
new FilesModule(),
new RomanModule(),
new CountryCapitalSearchModule(),
new GuestBookModule(),
new MoviesModule(),
};
static async Task Main(string[] args)
{
if (!HttpListener.IsSupported)
{
Console.WriteLine("HttpListener not supported!");
Environment.Exit(-1);
}
int port = GetPortFromArgs(args);
var listener = new HttpListener();
listener.Prefixes.Add($"http://+:{port.ToString()}/");
listener.Start();
while (true)
{
HttpListenerContext context = null;
try
{
context = listener.GetContext();
var module = modules.FirstOrDefault(m => m.CanProcess(context.Request)) ?? new UnhandledModule();
await module.ProcessAsync(context.Request, context.Response);
await context.Response.OutputStream.FlushAsync();
context.Response.OutputStream.Close();
}
catch (ApplicationException appEx)
{
Console.WriteLine($"ApplicationException: {appEx.Message}");
if (context == null)
{
continue;
}
await context.Response.JsRedirectWithMessageAsync($@"<h1>Error!!!!</h1>
</br>
{appEx.Message}
</br>
Redirecting in 3 seconds");
context.Response.OutputStream.Close();
}
catch (Exception ex)
{
Console.WriteLine($"Exception: {ex.Message}");
context?.Response?.OutputStream.Close();
}
}
}
private static int GetPortFromArgs(string[] args)
{
int port;
if (args?.Length != 2 || args[0] != "-p")
return defaultPort;
else if (!int.TryParse(args[1], out port))
return defaultPort;
return port;
}
}
}