-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProgram.cs
153 lines (123 loc) · 3.88 KB
/
Program.cs
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Console;
namespace quicklocalfileserver
{
public static class Program
{
private const int defaultPort = 12_000;
private static readonly string defaultDirectory = AppContext.BaseDirectory;
private static CancellationTokenSource cts = new CancellationTokenSource();
public static async Task<int> Main(string[] args)
{
ArgumentNullException.ThrowIfNull(args);
Console.CancelKeyPress += OnCancelPress;
int port = GetPort(args);
string directory = GetDirectory(args);
WebApplication webApplication = BuildWebApplication(port, directory);
try
{
await webApplication.StartAsync(cts.Token).ConfigureAwait(false);
await Console.Out.WriteLineAsync($"serving from '{directory}' on port {port}").ConfigureAwait(false);
await webApplication.WaitForShutdownAsync(cts.Token).ConfigureAwait(false);
}
finally
{
Console.CancelKeyPress -= OnCancelPress;
await webApplication.DisposeAsync().ConfigureAwait(false);
cts.Dispose();
}
return 0;
}
private static void OnCancelPress(object? sender, ConsoleCancelEventArgs e)
{
e.Cancel = true;
cts.Cancel();
}
private static int GetPort(string[] args)
{
return GetValueFromCommandLineArgs(args, "-p") switch
{
string value => Int32.TryParse(value, out int result) switch
{
true => IsPortInRange(result)
? result
: throw new ArgumentOutOfRangeException($"invalid port number ('{result}')"),
false => throw new ArgumentOutOfRangeException($"not an integer ('{value}')")
},
_ => defaultPort
};
}
private static bool IsPortInRange(int port)
{
return port > 1023 && port < 65536;
}
private static string GetDirectory(string[] args)
{
string? absolutePath = defaultDirectory;
if (GetValueFromCommandLineArgs(args, "-d") is string value)
{
if (value.Contains('~', StringComparison.Ordinal))
{
value = value.Replace(
"~",
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
StringComparison.Ordinal);
}
absolutePath = Path.IsPathRooted(value) ? value : Path.GetFullPath(value);
}
if (!Directory.Exists(absolutePath))
{
throw new DirectoryNotFoundException($"{absolutePath}");
}
return absolutePath;
}
private static string? GetValueFromCommandLineArgs(string[] args, string switchName)
{
for (int i = 0; i < args.Length; i++)
{
if (String.Equals(switchName, args[i], StringComparison.Ordinal))
{
if (i + 1 < args.Length)
{
return args[i + 1];
}
}
}
return null;
}
private static WebApplication BuildWebApplication(int port, string directory)
{
WebApplicationBuilder webAppBuilder = WebApplication.CreateBuilder(new WebApplicationOptions
{
ApplicationName = "quicklocalfileserver"
});
webAppBuilder.Logging.ClearProviders();
webAppBuilder.Logging.SetMinimumLevel(LogLevel.Warning);
webAppBuilder.Logging.AddSimpleConsole(static (SimpleConsoleFormatterOptions simpleConsoleFormatterOptions) =>
{
simpleConsoleFormatterOptions.ColorBehavior = LoggerColorBehavior.Enabled;
simpleConsoleFormatterOptions.IncludeScopes = true;
simpleConsoleFormatterOptions.SingleLine = true;
});
webAppBuilder.WebHost.UseKestrel((KestrelServerOptions kestrelServerOptions) =>
{
kestrelServerOptions.ListenLocalhost(port);
});
WebApplication webApplication = webAppBuilder.Build();
webApplication.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(directory)
});
return webApplication;
}
}
}