Innovenergy_trunk/csharp/App/OpenVpnCertificatesServer/Http.cs

48 lines
1.2 KiB
C#

using System.Net;
using Flurl;
namespace InnovEnergy.App.OpenVpnCertificatesServer;
public static class Http
{
// TODO: use worker thread
// TODO: could make it more efficient using TcpClient + SSL/TLS
public static void ServeGet(this String prefix, Func<Url, Byte[]?> f)
{
var listener = new HttpListener();
listener.Prefixes.Add(prefix);
listener.Start();
Console.WriteLine("Server started on " + prefix);
while (true)
{
var context = listener.GetContext();
var request = context.Request;
var response = context.Response;
if (request.HttpMethod.ToUpper() == "GET")
{
var url = new Url(request.Url?.OriginalString ?? "");
var reply = f(url);
if (reply != null)
{
using var stream = response.OutputStream;
stream.Write(reply);
}
else
{
response.StatusCode = 404;
}
}
else
response.StatusCode = 403;
response.Close();
}
// ReSharper disable once FunctionNeverReturns
}
}