HTTP.Example/Example/Program.cs
2024-10-28 06:57:01 +00:00

101 lines
3 KiB
C#

using System;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using MiniHTTP.Websockets;
using MiniHTTP.Responses;
using MiniHTTP.Routing;
namespace MiniHTTP.Example;
static class Program
{
static void Main(string[] args)
{
Console.WriteLine("Loading certificate");
X509Certificate2 cert = X509Certificate2.CreateFromPemFile("certs/example.net.crt", "certs/example.net.key");
if (OperatingSystem.IsWindows())
{
//Hack because SslStream is stupid on windows
using X509Certificate2 oldCert = cert;
cert = new X509Certificate2(oldCert.Export(X509ContentType.Pfx));
}
Console.WriteLine("Preparing listeners");
Router router = CreateRouter();
HttpServer httpServer = new HttpServer(80, null, router);
HttpServer httpsServer = new HttpServer(443, cert, router);
_ = httpServer.Start();
_ = httpsServer.Start();
Console.WriteLine($"Ready on ports {httpServer.Port} and {httpsServer.Port}");
Task.Delay(-1).Wait();
}
static Router CreateRouter()
{
//The order here matters
Router router = new Router();
router.Add(new CORS());
router.Add(HttpMethod.GET, "/variables/:param1/:param2", Variables);
router.Add(HttpMethod.GET, "/:file", Static.Create("www-static", "file"));
router.Add(HttpMethod.GET, "/:file", Static.Create("www-dynamic", "file"));
router.Add(HttpMethod.GET, "/", Root);
router.SetDefault(NotFound);
return router;
}
/// <summary>
/// Root endpoint: /
/// </summary>
static async Task<HttpResponse?> Root(HttpRequest req, RouteMatch route)
{
if (req.IsWebsocket)
return await Websocket(req, route);
byte[] indexFile = await File.ReadAllBytesAsync("www-static/index.htm");
HttpContent html = new HttpContent("text/html", indexFile);
return new OK(html);
}
/// <summary>
/// HTTP 404
/// </summary>
static NotFound NotFound(HttpRequest req, RouteMatch route)
{
return new NotFound("File not found");
}
/// <summary>
/// Variables endpoint
/// </summary>
static HttpResponse? Variables(HttpRequest req, RouteMatch route)
{
string? param1 = route.GetVariable("param1");
string? param2 = route.GetVariable("param1");
return new OK($"Variable 1: {param1}\nVariable 2: {param2}");
}
/// <summary>
/// Websocket endpoint
/// </summary>
static async Task<Empty> Websocket(HttpRequest client, RouteMatch route)
{
Websocket? ws = await client.UpgradeToWebsocket("test");
if (ws == null)
return new Empty();
DataFrame payload = await ws.Read();
if (payload.Opcode != WSOpcode.Close)
{
string result = payload.AsString();
await ws.Write(true, $"Echoing message: \"{result}\"");
}
ws.Close(CloseStatus.NormalClosure);
return new Empty();
}
}