Добавлен предсказуемый генератор данных

This commit is contained in:
Пытков Роман
2025-09-19 22:51:21 +03:00
parent 38f3880be8
commit c27e78cffe
11 changed files with 234 additions and 130 deletions

View File

@@ -14,12 +14,12 @@ public class HttpServer : IServer
private readonly HttpListener _listener;
private readonly string _url;
private CancellationTokenSource _cts = new CancellationTokenSource();
private Func<long, Data?> _getData;
private Func<Data?> _getPackage;
private Action<Data, HttpListenerResponse> _writeResponse;
public HttpServer(Func<long, Data?> getData, Action<Data, HttpListenerResponse> writeResponse, string url = "http://*:5555/")
public HttpServer(Func<Data?> getPackage, Action<Data, HttpListenerResponse> writeResponse, string url = "http://*:5555/")
{
_getData = getData;
_getPackage = getPackage;
_writeResponse = writeResponse;
_url = url;
_listener = new HttpListener();
@@ -63,28 +63,18 @@ public class HttpServer : IServer
{
if (context.Request.Url?.AbsolutePath.Equals("/fetchpackage", StringComparison.OrdinalIgnoreCase) == true)
{
string? indexStr = context.Request.QueryString["index"];
if (indexStr != null && long.TryParse(indexStr, out long index))
var data = _getPackage();
if (data != null)
{
var data = _getData(index);
if (data != null)
{
_writeResponse(data, context.Response);
}
else
{
var responseText = JsonSerializer.Serialize(new { error = "Data not found" });
context.Response.StatusCode = 404;
byte[] buffer = Encoding.UTF8.GetBytes(responseText);
context.Response.ContentType = "application/json";
context.Response.ContentLength64 = buffer.Length;
context.Response.OutputStream.Write(buffer, 0, buffer.Length);
}
_writeResponse(data, context.Response);
}
else
{
context.Response.StatusCode = 400;
byte[] buffer = Encoding.UTF8.GetBytes("Invalid or missing 'index' parameter.");
var responseText = JsonSerializer.Serialize(new { error = "Data not found" });
context.Response.StatusCode = 404;
byte[] buffer = Encoding.UTF8.GetBytes(responseText);
context.Response.ContentType = "application/json";
context.Response.ContentLength64 = buffer.Length;
context.Response.OutputStream.Write(buffer, 0, buffer.Length);
}
}