add health check

This commit is contained in:
Vinzenz Schroeter 2024-05-07 20:41:06 +02:00
parent de25b69a4b
commit 053bfb0d92
3 changed files with 115 additions and 10 deletions

View file

@ -1,7 +1,12 @@
using System.IO;
using System.Text;
using System.Text.Json;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using TanksServer.GameLogic;
using TanksServer.Interactivity;
@ -25,6 +30,11 @@ internal sealed class Endpoints(
app.MapGet("/map", () => mapService.MapNames);
app.MapPost("/map", PostMap);
app.MapGet("/map/{name}", GetMapByName);
app.MapHealthChecks("/health", new HealthCheckOptions
{
ResponseWriter = WriteJsonHealthCheckResponse
});
}
private Results<BadRequest<string>, NotFound<string>, Ok> PostMap([FromQuery] string name)
@ -107,4 +117,41 @@ internal sealed class Endpoints(
var mapInfo = new MapInfo(prototype.Name, prototype.GetType().Name, preview.Data);
return TypedResults.Ok(mapInfo);
}
private static Task WriteJsonHealthCheckResponse(HttpContext context, HealthReport healthReport)
{
context.Response.ContentType = "application/json; charset=utf-8";
var options = new JsonWriterOptions { Indented = true };
using var memoryStream = new MemoryStream();
using (var jsonWriter = new Utf8JsonWriter(memoryStream, options))
{
jsonWriter.WriteStartObject();
jsonWriter.WriteString("status", healthReport.Status.ToString());
jsonWriter.WriteStartObject("results");
foreach (var healthReportEntry in healthReport.Entries)
{
jsonWriter.WriteStartObject(healthReportEntry.Key);
jsonWriter.WriteString("status",
healthReportEntry.Value.Status.ToString());
jsonWriter.WriteString("description",
healthReportEntry.Value.Description);
jsonWriter.WriteStartObject("data");
foreach (var item in healthReportEntry.Value.Data)
jsonWriter.WriteString(item.Key, item.Value.ToString());
jsonWriter.WriteEndObject();
jsonWriter.WriteEndObject();
}
jsonWriter.WriteEndObject();
jsonWriter.WriteEndObject();
}
return context.Response.WriteAsync(
Encoding.UTF8.GetString(memoryStream.ToArray()));
}
}