-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStaticHandler.cs
More file actions
56 lines (42 loc) · 1.6 KB
/
Copy pathStaticHandler.cs
File metadata and controls
56 lines (42 loc) · 1.6 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
namespace Hint;
using System.Net;
using System.Text;
using System.IO;
public static class StaticHandler
{
public static async Task ServeStatic(HttpListenerResponse res, string root, string requestPath)
{
var localPath = requestPath.Replace('/', Path.DirectorySeparatorChar).TrimStart(Path.DirectorySeparatorChar);
var file = string.IsNullOrEmpty(localPath)
? Path.Combine(root, "index.html")
: Path.Combine(root, localPath);
Console.WriteLine($"[LOG] Static file path: {file}");
if (Directory.Exists(file)) file = Path.Combine(file, "index.html");
if (!File.Exists(file))
{
Console.WriteLine($"[ERROR] File not found: {file}");
res.StatusCode = 404;
var bytes = Encoding.UTF8.GetBytes("Not Found");
res.ContentType = "text/plain; charset=utf-8";
await res.OutputStream.WriteAsync(bytes);
return;
}
Console.WriteLine($"[LOG] Serving file: {file}");
var ct = GetContentType(Path.GetExtension(file));
res.ContentType = ct;
using var fs = File.OpenRead(file);
await fs.CopyToAsync(res.OutputStream);
}
private static string GetContentType(string ext) => ext.ToLowerInvariant() switch
{
".html" => "text/html; charset=utf-8",
".css" => "text/css",
".js" => "application/javascript",
".png" => "image/png",
".jpg" => "image/jpeg",
".jpeg" => "image/jpeg",
".gif" => "image/gif",
".json" => "application/json",
_ => "application/octet-stream"
};
}