49 lines
1.2 KiB
C#
49 lines
1.2 KiB
C#
|
namespace InnovEnergy.OpenVpnCertificatesServer;
|
||
|
|
||
|
using System;
|
||
|
using System.Net;
|
||
|
using Flurl;
|
||
|
|
||
|
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
|
||
|
}
|
||
|
}
|