-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
82 lines (62 loc) · 2.54 KB
/
Copy pathProgram.cs
File metadata and controls
82 lines (62 loc) · 2.54 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
namespace Hint;
using System.Net;
using System.Text;
using System.Text.Json;
using System.IO;
class Program
{
static async Task Main(string[] args)
{
var configPath = "serverconfig.json";
var config = File.Exists(configPath)
? JsonSerializer.Deserialize<ServerConfig>(File.ReadAllText(configPath)) ?? new ServerConfig()
: new ServerConfig();
var exeDir = AppContext.BaseDirectory;
config = config with { StaticRoot = Path.Combine(exeDir, config.StaticRoot) };
Console.WriteLine($"[LOG] Static root: {config.StaticRoot}");
var listener = new HttpListener();
listener.Prefixes.Add($"http://*:{config.Port}/");
listener.Start();
var appManager = new AppManager(config.Apps);
_ = appManager.EnsureAllRunningAsync();
Console.WriteLine($"[LOG] Listening on port {config.Port}");
while (true)
{
var ctx = await listener.GetContextAsync();
_ = Task.Run(async () =>
{
var req = ctx.Request;
var res = ctx.Response;
Console.WriteLine($"[LOG] Incoming request: {req.HttpMethod} {req.Url.AbsolutePath}");
try
{
var path = req.Url.AbsolutePath.TrimStart('/');
var segments = path.Split('/', StringSplitOptions.RemoveEmptyEntries);
if (segments.Length > 0 && appManager.TryGetApp(segments[0], out var app))
{
Console.WriteLine($"[LOG] Forwarding request to app: {app.Name}");
var forwardPath = "/" + string.Join('/', segments.Skip(1));
await ProxyHandler.ProxyRequest(res, req, app, forwardPath);
}
else
{
Console.WriteLine($"[LOG] Serving static: {path}");
await StaticHandler.ServeStatic(res, config.StaticRoot, req.Url.AbsolutePath);
}
}
catch (Exception ex)
{
Console.WriteLine($"[ERROR] {ex}");
var bytes = Encoding.UTF8.GetBytes(ex.ToString());
res.StatusCode = 500;
res.ContentType = "text/plain; charset=utf-8";
await res.OutputStream.WriteAsync(bytes);
}
finally
{
res.OutputStream.Close();
}
});
}
}
}