minimal optimizations

This commit is contained in:
2024-10-24 09:11:45 +02:00
parent 24266789e8
commit b2a1cc2da8
2 changed files with 49 additions and 11 deletions

View File

@@ -67,16 +67,18 @@ public class ApiClient(string apiUrl) : IApiClient
Log.DebugFormat("Api endpoint url is {0}", url);
Log.Debug("Create content");
if (message is not null)
content = new StringContent(serializer.Serialize(message)!, null, "application/json");
else
content = new StringContent(string.Empty, null, "application/json");
Log.Debug("Content created.");
Log.Debug("Build headers");
content.Headers.Add("API-AUTH-KEY", EncodeAuthKey());
Log.Debug("Sending request...");
Log.Debug("Sending request");
return await httpClient.PostAsync(url, content);
}

View File

@@ -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);