forked from PGR/ascnet
1
0
Fork 0
ascnet/AscNet.SDKServer/SDKServer.cs

77 lines
2.4 KiB
C#
Raw Permalink Normal View History

using AscNet.Logging;
2023-10-06 13:29:27 +00:00
namespace AscNet.SDKServer
{
public class SDKServer
{
public static readonly Logger log = new(typeof(SDKServer), Logging.LogLevel.DEBUG, Logging.LogLevel.DEBUG);
2023-10-06 13:29:27 +00:00
public static void Main(string[] args)
{
log.LogLevelColor[Logging.LogLevel.INFO] = ConsoleColor.Blue;
2023-10-06 13:29:27 +00:00
var builder = WebApplication.CreateBuilder(args);
// Disables default logger
builder.Logging.ClearProviders();
var app = builder.Build();
app.Urls.Add("http://*:80");
app.Urls.Add("https://*:443");
IEnumerable<Type> controllers = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(s => s.GetTypes())
.Where(p => typeof(IRegisterable).IsAssignableFrom(p) && !p.IsInterface)
.Select(x => x);
foreach (Type controller in controllers)
{
controller.GetMethod(nameof(IRegisterable.Register))!.Invoke(null, new object[] { app });
#if DEBUG
log.Info($"Registered HTTP controller '{controller.Name}'");
2023-10-06 13:29:27 +00:00
#endif
}
app.UseMiddleware<RequestLoggingMiddleware>();
new Thread(() => app.Run()).Start();
log.Info($"{nameof(SDKServer)} started in port {string.Join(", ", app.Urls.Select(x => x.Split(':').Last()))}!");
2023-10-06 13:29:27 +00:00
}
private class RequestLoggingMiddleware
{
private readonly RequestDelegate _next;
2023-10-16 09:50:49 +00:00
private static readonly string[] SurpressedRoutes = new string[] { "/feedback" };
2023-10-06 13:29:27 +00:00
public RequestLoggingMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
try
{
await _next(context);
}
2023-10-19 07:07:48 +00:00
catch (Exception ex)
{
#if DEBUG
log.Error($"{ex} Request below:");
#else
2023-10-19 07:07:48 +00:00
log.Error($"{ex.Message} Request below:");
#endif
2023-10-19 07:07:48 +00:00
}
2023-10-06 13:29:27 +00:00
finally
{
log.Info($"{context.Response.StatusCode} {context.Request.Method.ToUpper()} {context.Request.Path + context.Request.QueryString}");
2023-10-06 13:29:27 +00:00
}
}
}
}
public interface IRegisterable
{
public abstract static void Register(WebApplication app);
}
}