minimal optimizations
This commit is contained in:
@@ -24,12 +24,14 @@ public class ApiServer(string apiUrl) : IApiServer
|
||||
|
||||
public ILogger Log { get; set; } = NullLogger.Instance;
|
||||
|
||||
public bool DebugMode { get; set; }
|
||||
|
||||
public virtual void Start()
|
||||
{
|
||||
Log.Info("Start listening");
|
||||
httpListener.Prefixes.Add(ApiUrl + "/");
|
||||
httpListener.Start();
|
||||
Task.Run(Listen);
|
||||
Receive();
|
||||
}
|
||||
|
||||
public virtual void Stop()
|
||||
@@ -72,18 +74,52 @@ public class ApiServer(string apiUrl) : IApiServer
|
||||
handlers.Add(fullUrl, handler);
|
||||
}
|
||||
|
||||
protected virtual void Listen()
|
||||
protected void Receive()
|
||||
{
|
||||
while (httpListener.IsListening)
|
||||
CheckContext();
|
||||
httpListener?.BeginGetContext(ListenerCallback, null);
|
||||
}
|
||||
|
||||
protected virtual void CheckContext()
|
||||
protected void ListenerCallback(IAsyncResult result)
|
||||
{
|
||||
var context = httpListener.GetContext();
|
||||
HttpListenerContext context;
|
||||
|
||||
// Skip if not lisstening anymore
|
||||
if (!httpListener.IsListening)
|
||||
return;
|
||||
|
||||
// Get context
|
||||
try
|
||||
{
|
||||
context = httpListener.EndGetContext(result);
|
||||
}
|
||||
catch (HttpListenerException)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Immitatly listen for new request
|
||||
Receive();
|
||||
|
||||
// Check context
|
||||
try
|
||||
{
|
||||
CheckContext(context);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log.Error(ex.ToString());
|
||||
if (DebugMode)
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
protected virtual void CheckContext(HttpListenerContext context)
|
||||
{
|
||||
Log.Info("Start handling request");
|
||||
|
||||
void close()
|
||||
{
|
||||
Log.Info("End handling request.");
|
||||
Log.Info("End handling request");
|
||||
context.Response.OutputStream.Close();
|
||||
}
|
||||
|
||||
@@ -137,10 +173,10 @@ public class ApiServer(string apiUrl) : IApiServer
|
||||
context.Response.StatusCode = (int)result.Original.StatusCode;
|
||||
|
||||
// Write response content
|
||||
Log.Debug("Write response");
|
||||
Log.Debug("Create response");
|
||||
if (result.ResultJson is not null)
|
||||
{
|
||||
Log.Info("Write response");
|
||||
Log.Info("Sending response");
|
||||
context.Response.ContentType = "application/json";
|
||||
using StreamWriter output = new(context.Response.OutputStream);
|
||||
output.Write(result.ResultJson);
|
||||
|
||||
Reference in New Issue
Block a user