97 lines
3.1 KiB
C#
97 lines
3.1 KiB
C#
using System.Linq;
|
|
using System.Net;
|
|
using System.Text.Encodings.Web;
|
|
using System.Text.Json.Serialization;
|
|
using DTLib.Extensions;
|
|
|
|
namespace ParadoxSaveParser.WebAPI;
|
|
|
|
public partial class Program
|
|
{
|
|
private static readonly JsonSerializerOptions _responseJsonSerializerOptions = new()
|
|
{
|
|
WriteIndented = false,
|
|
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
|
|
MaxDepth = 1024
|
|
};
|
|
|
|
public static async Task<HttpStatusCode> ReturnResponseString(HttpListenerContext ctx,
|
|
string value, HttpStatusCode statusCode = HttpStatusCode.OK)
|
|
{
|
|
ctx.Response.StatusCode = (int)statusCode;
|
|
ctx.Response.ContentType = "text/plain";
|
|
await ctx.Response.OutputStream.WriteAsync(
|
|
value.ToBytes(),
|
|
_mainCancel.Token);
|
|
return statusCode;
|
|
}
|
|
|
|
public static async Task<HttpStatusCode> ReturnResponseJson(HttpListenerContext ctx,
|
|
object value, HttpStatusCode statusCode = HttpStatusCode.OK)
|
|
{
|
|
ctx.Response.StatusCode = (int)statusCode;
|
|
ctx.Response.ContentType = "application/json";
|
|
await JsonSerializer.SerializeAsync(
|
|
ctx.Response.OutputStream,
|
|
value,
|
|
value.GetType(),
|
|
_responseJsonSerializerOptions,
|
|
_mainCancel.Token);
|
|
return statusCode;
|
|
}
|
|
|
|
public static async Task<HttpStatusCode> ReturnResponseError(HttpListenerContext ctx, ErrorMessage error)
|
|
{
|
|
ctx.Response.StatusCode = (int)error.StatusCode;
|
|
ctx.Response.ContentType = "application/json";
|
|
await JsonSerializer.SerializeAsync(
|
|
ctx.Response.OutputStream,
|
|
error,
|
|
typeof(ErrorMessage),
|
|
_responseJsonSerializerOptions,
|
|
_mainCancel.Token);
|
|
return error.StatusCode;
|
|
}
|
|
|
|
public record ErrorMessage
|
|
{
|
|
public ErrorMessage(HttpStatusCode statusCode, string message)
|
|
{
|
|
StatusCode = statusCode;
|
|
Message = message;
|
|
}
|
|
|
|
[JsonIgnore] public HttpStatusCode StatusCode { get; }
|
|
|
|
[JsonPropertyName("errorMessage")] public string Message { get; }
|
|
}
|
|
|
|
public class ValueOrError<T>
|
|
{
|
|
public readonly ErrorMessage? Error;
|
|
public readonly T? Value;
|
|
|
|
private ValueOrError(T? value, ErrorMessage? error)
|
|
{
|
|
Value = value;
|
|
Error = error;
|
|
}
|
|
|
|
public bool HasError => Error is not null;
|
|
|
|
public static implicit operator ValueOrError<T>(T v) => new(v, null);
|
|
|
|
public static implicit operator ValueOrError<T>(ErrorMessage e) => new(default, e);
|
|
}
|
|
|
|
|
|
internal static ValueOrError<string> GetRequestQueryValue(HttpListenerContext ctx, string paramName)
|
|
{
|
|
string[]? values = ctx.Request.QueryString.GetValues(paramName);
|
|
string? value = values?.FirstOrDefault();
|
|
if (string.IsNullOrEmpty(value))
|
|
return new ErrorMessage(HttpStatusCode.BadRequest,
|
|
$"No request parameter '{paramName}' provided");
|
|
return value;
|
|
}
|
|
} |