From 2948fe284b2f81f8cbcc9696fbc947f96da8bb64 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andreas=20N=C3=A4geli?= Date: Fri, 30 Oct 2026 16:11:16 +0100 Subject: [PATCH 1/4] feat(playground): Add a graphical web app to the playground --- Playground/Browser/Catalog.cs | 161 +++ Playground/Browser/Index.html | 987 ++++++++++++++++++ Playground/Browser/Sample.cs | 30 + Playground/Browser/SampleBrowser.cs | 43 + Playground/GenHTTP.Playground.csproj | 19 +- Playground/Program.cs | 16 +- Playground/README.md | 57 +- Playground/Resources/Spa/app.js | 24 + Playground/Resources/Spa/index.html | 17 + Playground/Resources/Website/about/index.html | 12 + Playground/Resources/Website/index.html | 13 + Playground/Resources/Website/styles.css | 6 + Playground/Samples/ApiDocumentationSample.cs | 75 ++ Playground/Samples/AuthenticationSample.cs | 92 ++ Playground/Samples/ControllerSample.cs | 10 +- Playground/Samples/CorsSample.cs | 39 + Playground/Samples/CustomFrameworkSample.cs | 4 +- .../Samples/DependencyInjectionSample.cs | 99 ++ Playground/Samples/ErrorHandlingSample.cs | 77 ++ Playground/Samples/FileShareSample.cs | 37 + Playground/Samples/FunctionalSample.cs | 8 +- Playground/Samples/InspectionSample.cs | 36 + Playground/Samples/LayoutingSample.cs | 4 +- Playground/Samples/LegacyMigrationSample.cs | 49 + Playground/Samples/LoadBalancerSample.cs | 44 + Playground/Samples/LocalizationSample.cs | 53 + Playground/Samples/McpSample.cs | 14 +- Playground/Samples/PagesSample.cs | 82 ++ Playground/Samples/ServerSentEventsSample.cs | 88 ++ .../Samples/SinglePageApplicationSample.cs | 7 +- Playground/Samples/StaticFileSample.cs | 4 +- Playground/Samples/StaticWebsiteSample.cs | 4 +- Playground/Samples/VirtualHostingSample.cs | 38 + Playground/Samples/WebserviceSample.cs | 8 +- Playground/Samples/WebsocketSample.cs | 143 +++ 35 files changed, 2364 insertions(+), 36 deletions(-) create mode 100644 Playground/Browser/Catalog.cs create mode 100644 Playground/Browser/Index.html create mode 100644 Playground/Browser/Sample.cs create mode 100644 Playground/Browser/SampleBrowser.cs create mode 100644 Playground/Resources/Spa/app.js create mode 100644 Playground/Resources/Spa/index.html create mode 100644 Playground/Resources/Website/about/index.html create mode 100644 Playground/Resources/Website/index.html create mode 100644 Playground/Resources/Website/styles.css create mode 100644 Playground/Samples/ApiDocumentationSample.cs create mode 100644 Playground/Samples/AuthenticationSample.cs create mode 100644 Playground/Samples/CorsSample.cs create mode 100644 Playground/Samples/DependencyInjectionSample.cs create mode 100644 Playground/Samples/ErrorHandlingSample.cs create mode 100644 Playground/Samples/FileShareSample.cs create mode 100644 Playground/Samples/InspectionSample.cs create mode 100644 Playground/Samples/LegacyMigrationSample.cs create mode 100644 Playground/Samples/LoadBalancerSample.cs create mode 100644 Playground/Samples/LocalizationSample.cs create mode 100644 Playground/Samples/PagesSample.cs create mode 100644 Playground/Samples/ServerSentEventsSample.cs create mode 100644 Playground/Samples/VirtualHostingSample.cs create mode 100644 Playground/Samples/WebsocketSample.cs diff --git a/Playground/Browser/Catalog.cs b/Playground/Browser/Catalog.cs new file mode 100644 index 000000000..71fe4eab0 --- /dev/null +++ b/Playground/Browser/Catalog.cs @@ -0,0 +1,161 @@ +using GenHTTP.Playground.Samples; + +namespace GenHTTP.Playground.Browser; + +/// +/// All samples served by the playground, with the requests the +/// sample browser offers to try them. +/// +internal static class Catalog +{ + private const string Docs = "https://genhttp.org/documentation/content/"; + + private static readonly Dictionary Json = new() { ["Content-Type"] = "application/json" }; + + internal static readonly List Samples = + [ + // Frameworks + + new("webservices", "Frameworks", "Webservices", "Implements a REST webservice via a handler class.", + Docs + "frameworks/webservices/", "WebserviceSample.cs", WebserviceSample.Create(), + Example.Request("List all books", "GET", "/webservices/books/"), + Example.Request("Add a book", "PUT", "/webservices/books/", """{ "title": "The Hobbit" }""", Json), + Example.Request("Delete a book", "DELETE", "/webservices/books/1")), + + new("functional", "Frameworks", "Functional", "Uses delegates to implement a web service (similar to ASP.NET Core Minimal API).", + Docs + "frameworks/functional/", "FunctionalSample.cs", FunctionalSample.Create(), + Example.Request("List all books", "GET", "/functional/books/"), + Example.Request("Add a book", "PUT", "/functional/books/", """{ "title": "The Hobbit" }""", Json), + Example.Request("Delete a book", "DELETE", "/functional/books/1")), + + new("controllers", "Frameworks", "Controllers", "Uses controllers to implement a web service (similar to ASP.NET Core MVC).", + Docs + "frameworks/controllers/", "ControllerSample.cs", ControllerSample.Create(), + Example.Request("List all books", "GET", "/controllers/books/"), + Example.Request("Add a book", "PUT", "/controllers/books/create/", """{ "title": "The Hobbit" }""", Json), + Example.Request("Delete a book", "DELETE", "/controllers/books/delete/1/")), + + new("websockets", "Frameworks", "Websockets", "A chat room that pushes messages to all connected browsers.", + Docs + "frameworks/websockets/", "WebsocketSample.cs", WebsocketSample.Create(), + Example.Page("Open the chat", "/websockets/", "Open it twice to chat with yourself.")), + + new("mcp", "Frameworks", "MCP Tools", "Provides tools to AI agents such as Claude via the Model Context Protocol.", + Docs + "frameworks/mcp/", "McpSample.cs", McpSample.Create(), + Example.Shell("Add the server to Claude Code", "claude mcp add --transport http library {origin}/mcp", + "Then ask Claude \"Which books about Rome are in the library?\""), + Example.Request("List the tools, as an agent would", "POST", "/mcp/", """{ "jsonrpc": "2.0", "id": 1, "method": "tools/list" }""", Json), + Example.Request("Call a tool", "POST", "/mcp/", """{ "jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": { "name": "find_books", "arguments": { "query": "Rome" } } }""", Json)), + + new("static-website", "Frameworks", "Static Websites", "Hosts a static website (with index.html support).", + Docs + "frameworks/static-websites/", "StaticWebsiteSample.cs", StaticWebsiteSample.Create(), + Example.Page("Open the website", "/static-website/")), + + new("spa", "Frameworks", "Single Page Applications", "Hosts a SPA such as a React or Angular application.", + Docs + "frameworks/single-page-applications/", "SinglePageApplicationSample.cs", SinglePageApplicationSample.Create(), + Example.Page("Open the application", "/spa/"), + Example.Page("Open a client side route directly", "/spa/books/42", "The server delivers the application, which then renders the route.")), + + new("custom-framework", "Frameworks", "Custom Frameworks", "Builds your own framework on top of the reflection layer.", + Docs + "frameworks/custom/", "CustomFrameworkSample.cs", CustomFrameworkSample.Create(), + Example.Request("Call the exposed method", "GET", "/custom-framework/42"), + Example.Page("Browse the generated API", "/custom-framework/scalar/")), + + // Handlers + + new("layouting", "Handlers", "Layouting", "Allows an app to use multiple handlers by adding routing.", + Docs + "handlers/layouting/", "LayoutingSample.cs", LayoutingSample.Create(), + Example.Request("Call the API", "GET", "/layouting/api/"), + Example.Request("Fetch a file", "GET", "/layouting/assets/README.md")), + + new("static-files", "Handlers", "Static Files", "Serves static files from a directory.", + Docs + "handlers/files/", "StaticFileSample.cs", StaticFileSample.Create(), + Example.Request("Fetch a file", "GET", "/static-files/README.md")), + + new("api-docs", "Handlers", "API Documentation", "Generates an Open API definition and serves Swagger UI, Redoc and Scalar.", + Docs + "handlers/api-browsing/", "ApiDocumentationSample.cs", ApiDocumentationSample.Create(), + Example.Page("Swagger UI", "/api-docs/swagger/"), + Example.Page("Redoc", "/api-docs/redoc/"), + Example.Page("Scalar", "/api-docs/scalar/"), + Example.Request("Fetch the Open API definition", "GET", "/api-docs/openapi.json"), + Example.Request("Fetch a book that does not exist", "GET", "/api-docs/books/42", note: "404, as documented in the definition")), + + new("sse", "Handlers", "Server Sent Events", "A live dashboard that receives updates pushed by the server.", + Docs + "handlers/server-sent-events/", "ServerSentEventsSample.cs", ServerSentEventsSample.Create(), + Example.Page("Open the dashboard", "/sse/"), + Example.Shell("Watch the raw event stream", "curl -N {origin}/sse/stats/")), + + new("pages", "Handlers", "Pages", "Renders HTML pages from templates on the server.", + Docs + "handlers/pages/", "PagesSample.cs", PagesSample.Create(), + Example.Page("Page rendered from a template", "/pages/books/"), + Example.Page("Page in the server style", "/pages/about/")), + + new("virtual-hosting", "Handlers", "Virtual Hosting", "Hosts multiple websites, one per domain, on a single server.", + Docs + "handlers/virtual-hosts/", "VirtualHostingSample.cs", VirtualHostingSample.Create(), + Example.Page("Open the blog", "http://blog.localhost:8080/virtual-hosting/"), + Example.Page("Open the shop", "http://shop.localhost:8080/virtual-hosting/"), + Example.Page("Open with any other host", "/virtual-hosting/", "Redirects to the blog."), + Example.Shell("Choose the site via the Host header", "curl -H \"Host: shop.localhost\" {origin}/virtual-hosting/")), + + new("load-balancing", "Handlers", "Load Balancing", "Distributes requests over workers and mirrors, with a canary deployment.", + Docs + "handlers/load-balancer/", "LoadBalancerSample.cs", LoadBalancerSample.Create(), + Example.Request("Call a worker", "GET", "/load-balancing/api/", note: "502, unless workers run on ports 5001 and 5002"), + Example.Request("Call the canary worker", "GET", "/load-balancing/api/", headers: new() { ["X-Canary"] = "1" }, note: "502, unless a worker runs on port 5003"), + Example.Shell("Download from a mirror", "curl -i {origin}/load-balancing/downloads/setup.exe", "Redirects to one of the mirrors.")), + + // Concerns + + new("authentication", "Concerns", "Authentication", "Secures an API with API keys, roles and per-user data.", + Docs + "concerns/authentication/", "AuthenticationSample.cs", AuthenticationSample.Create(), + Example.Request("Add a note as Alice", "PUT", "/authentication/notes/", "Buy milk", new() { ["X-API-Key"] = "alice-key", ["Content-Type"] = "text/plain" }), + Example.Request("List the notes of Alice", "GET", "/authentication/notes/", headers: new() { ["X-API-Key"] = "alice-key" }), + Example.Request("List all notes as Alice", "GET", "/authentication/notes/all", headers: new() { ["X-API-Key"] = "alice-key" }, note: "403, Alice is no administrator"), + Example.Request("List all notes as Bob", "GET", "/authentication/notes/all", headers: new() { ["X-API-Key"] = "bob-key" }), + Example.Request("Call without a key", "GET", "/authentication/notes/", note: "401")), + + new("cors", "Concerns", "CORS", "Allows a frontend on another origin to call the API from the browser.", + Docs + "concerns/cors/", "CorsSample.cs", CorsSample.Create(), + Example.Request("List the todos", "GET", "/cors/api/todos/"), + Example.Shell("Send the preflight request of the frontend", + "curl -i -X OPTIONS -H \"Origin: http://localhost:5173\" -H \"Access-Control-Request-Method: PUT\" {origin}/cors/api/todos/", + "Browsers send this before the actual request. Try another origin to see the CORS headers disappear.")), + + new("errors", "Concerns", "Error Handling", "JSON errors for the API, HTML error pages for the website, custom mapping.", + Docs + "concerns/error-handling/", "ErrorHandlingSample.cs", ErrorHandlingSample.Create(), + Example.Request("Fetch an order", "GET", "/errors/api/orders/1"), + Example.Request("Fetch an order that does not exist", "GET", "/errors/api/orders/42", note: "404 as JSON"), + Example.Request("Order something that is sold out", "POST", "/errors/api/orders/", """{ "product": "Tea" }""", Json, "409, mapped from a custom exception"), + Example.Page("Open a page that does not exist", "/errors/does-not-exist", "404 as HTML page")), + + new("localization", "Concerns", "Localization", "Responds in the language preferred by the user.", + Docs + "concerns/localization/", "LocalizationSample.cs", LocalizationSample.Create(), + Example.Request("Prefer Swiss German", "GET", "/localization/greeting/", headers: new() { ["Accept-Language"] = "de-CH, en;q=0.8" }), + Example.Request("Choose French", "GET", "/localization/greeting/?lang=fr"), + Example.Request("Prefer Japanese", "GET", "/localization/greeting/", headers: new() { ["Accept-Language"] = "ja" }, note: "Not supported, falls back to English")), + + new("inspection", "Concerns", "Inspection", "Shows what the server received and responded, to debug clients.", + Docs + "concerns/inspection/", "InspectionSample.cs", InspectionSample.Create(), + Example.Request("Call the API", "GET", "/inspection/api/orders/?limit=5"), + Example.Request("Inspect the call", "GET", "/inspection/api/orders/?limit=5&inspect")), + + // Concepts + + new("dependency-injection", "Concepts", "Dependency Injection", "Lets the framework construct services and pass dependencies.", + Docs + "concepts/dependency-injection/", "DependencyInjectionSample.cs", DependencyInjectionSample.Create(), + Example.Request("List all books", "GET", "/dependency-injection/books/"), + Example.Request("Add a book", "PUT", "/dependency-injection/books/", """{ "title": "Dune" }""", Json)), + + // Use cases + + new("file-share", "Use Cases", "File Share", "Password protected directory listing with resumable downloads.", + Docs + "handlers/listing/", "FileShareSample.cs", FileShareSample.Create(), + Example.Page("Browse the files", "/file-share/", "Log in as \"friend\" with password \"secret\"."), + Example.Request("Download the first 100 bytes of a file", "GET", "/file-share/README.md", + headers: new() { ["Authorization"] = "Basic ZnJpZW5kOnNlY3JldA==", ["Range"] = "bytes=0-99" }, note: "206 Partial Content")), + + new("legacy-migration", "Use Cases", "Legacy Migration", "Replaces a legacy app step by step using a reverse proxy, redirects and new endpoints.", + Docs + "handlers/reverse-proxy/", "LegacyMigrationSample.cs", LegacyMigrationSample.Create(), + Example.Request("Call the rewritten API", "GET", "/legacy-migration/api/v2/status"), + Example.Request("Open a page that has moved", "GET", "/legacy-migration/contact.php", note: "301 to the rewritten page"), + Example.Request("Open a page of the legacy app", "GET", "/legacy-migration/login.php", note: "502, unless the legacy app runs on port 5000")) + ]; + +} diff --git a/Playground/Browser/Index.html b/Playground/Browser/Index.html new file mode 100644 index 000000000..d7bc386c5 --- /dev/null +++ b/Playground/Browser/Index.html @@ -0,0 +1,987 @@ + + + + + + GenHTTP Playground + + + + + + +
+ + + + + diff --git a/Playground/Browser/Sample.cs b/Playground/Browser/Sample.cs new file mode 100644 index 000000000..4ca509e3b --- /dev/null +++ b/Playground/Browser/Sample.cs @@ -0,0 +1,30 @@ +using System.Text.Json.Serialization; + +using GenHTTP.Api.Content; + +namespace GenHTTP.Playground.Browser; + +/// The path the sample is served at, e.g. "webservices" for http://localhost:8080/webservices/ +/// The file name of the sample within the Samples folder +public sealed record Sample(string Segment, string Category, string Name, string Description, string Documentation, string Source, + [property: JsonIgnore] IHandlerBuilder Handler, params Example[] Examples); + +/// +/// A way to try a sample: a request sent from the sample browser, a page +/// opened in the browser or a shell command ("{origin}" is replaced by the +/// URL of the playground). +/// +public sealed record Example(string Kind, string Title, string? Method = null, string? Path = null, string? Body = null, + Dictionary? Headers = null, string? Command = null, string? Note = null) +{ + + public static Example Request(string title, string method, string path, string? body = null, Dictionary? headers = null, string? note = null) + => new("request", title, method, path, body, headers, Note: note); + + public static Example Page(string title, string path, string? note = null) + => new("page", title, Path: path, Note: note); + + public static Example Shell(string title, string command, string? note = null) + => new("shell", title, Command: command, Note: note); + +} diff --git a/Playground/Browser/SampleBrowser.cs b/Playground/Browser/SampleBrowser.cs new file mode 100644 index 000000000..7c6cf702f --- /dev/null +++ b/Playground/Browser/SampleBrowser.cs @@ -0,0 +1,43 @@ +using GenHTTP.Api.Content; +using GenHTTP.Api.Protocol; + +using GenHTTP.Modules.Functional; +using GenHTTP.Modules.IO; +using GenHTTP.Modules.Layouting; + +namespace GenHTTP.Playground.Browser; + +/// +/// Serves all samples below their own path, together with a page +/// at the root that lists them and allows to call them. +/// +internal static class SampleBrowser +{ + private static readonly ContentType SourceType = new("text/plain; charset=utf-8"); + + internal static IHandlerBuilder Create() + { + var sources = Layout.Create(); + + foreach (var sample in Catalog.Samples) + { + sources.Add(sample.Source, Content.From(Resource.FromAssembly($"Source.{sample.Source}").Type(SourceType))); + } + + var playground = Layout.Create() + .Add("samples", Inline.Create().Get(() => Catalog.Samples)) + .Add("source", sources); + + var app = Layout.Create() + .Index(Content.From(Resource.FromAssembly("Browser.Index.html"))) + .Add("playground", playground); + + foreach (var sample in Catalog.Samples) + { + app.Add(sample.Segment, sample.Handler); + } + + return app; + } + +} diff --git a/Playground/GenHTTP.Playground.csproj b/Playground/GenHTTP.Playground.csproj index 8baea9af3..f0ceac292 100644 --- a/Playground/GenHTTP.Playground.csproj +++ b/Playground/GenHTTP.Playground.csproj @@ -3,7 +3,7 @@ Exe - net11.0 + net11.0 true false @@ -40,6 +40,7 @@ + @@ -56,4 +57,20 @@ + + + + + + + + + + + + + + + + diff --git a/Playground/Program.cs b/Playground/Program.cs index 8ff2060cb..019eaa8e8 100644 --- a/Playground/Program.cs +++ b/Playground/Program.cs @@ -1,13 +1,25 @@ using GenHTTP.Engine.Internal; +using GenHTTP.Modules.DependencyInjection; using GenHTTP.Modules.Practices; +using GenHTTP.Playground.Browser; using GenHTTP.Playground.Samples; -var sample = LayoutingSample.Create(); +/* + * + * Serves all samples, open http://localhost:8080/ to browse them and call them + * from your browser. To run a single sample, pass it to the host instead, e.g. + * + * .Handler(WebserviceSample.Create()) + * + * The samples for the ioxide engine create their own host, see Samples/Ioxide/README.md. + * + */ return await Host.Create() - .Handler(sample) + .Handler(SampleBrowser.Create()) + .AddDependencyInjection(DependencyInjectionSample.Services()) .Development() .Defaults() .RunAsync(); diff --git a/Playground/README.md b/Playground/README.md index 2f6dfdfe6..b300abde6 100644 --- a/Playground/README.md +++ b/Playground/README.md @@ -3,13 +3,66 @@ The playground provides code samples for quick reference and allows developers to quickly validate things. +```bash +cd Playground +dotnet run +``` + +Then open http://localhost:8080/ to browse the samples, read their code and call them +from your browser (or copy the equivalent `curl` command). All samples run on this one +server, each below its own path, e.g. `/webservices/`. + +To add a sample, create a class in [Samples](./Samples) with a `Create()` method returning +the handler and register it with a few example requests in [Browser/Catalog.cs](./Browser/Catalog.cs). + +## Frameworks + | Sample | Description | |----------------------------------------------------------------------|----------------------------------------------------------------------------------| -| [Layouting](./Samples/LayoutingSample.cs) | Allows an app to use multiple handlers by adding routing. | | [Webservices](./Samples/WebserviceSample.cs) | Implements a REST webservice via a handler class. | | [Functional](./Samples/FunctionalSample.cs) | Uses delegates to implement a web service (similar to ASP.NET Core Minimal API). | | [Controllers](./Samples/ControllerSample.cs) | Uses controllers to implement a web service (similar to ASP.NET Core MVC). | +| [Websockets](./Samples/WebsocketSample.cs) | A chat room that pushes messages to all connected browsers. | | [MCP Tools](./Samples/McpSample.cs) | Provides tools to AI agents such as Claude via the Model Context Protocol. | -| [Static Files](./Samples/StaticFileSample.cs) | Serves static files from a directory. | | [Static Websites](./Samples/StaticWebsiteSample.cs) | Hosts a static website (with `index.html` support). | | [Single Page Applications](./Samples/SinglePageApplicationSample.cs) | Hosts a SPA such as a React or Angular application. | +| [Custom Frameworks](./Samples/CustomFrameworkSample.cs) | Builds your own framework on top of the reflection layer. | + +## Handlers + +| Sample | Description | +|---------------------------------------------------------|-----------------------------------------------------------------------------| +| [Layouting](./Samples/LayoutingSample.cs) | Allows an app to use multiple handlers by adding routing. | +| [Static Files](./Samples/StaticFileSample.cs) | Serves static files from a directory. | +| [API Documentation](./Samples/ApiDocumentationSample.cs) | Generates an Open API definition and serves Swagger UI, Redoc and Scalar. | +| [Server Sent Events](./Samples/ServerSentEventsSample.cs) | A live dashboard that receives updates pushed by the server. | +| [Pages](./Samples/PagesSample.cs) | Renders HTML pages from templates on the server. | +| [Virtual Hosting](./Samples/VirtualHostingSample.cs) | Hosts multiple websites, one per domain, on a single server. | +| [Load Balancing](./Samples/LoadBalancerSample.cs) | Distributes requests over workers and mirrors, with a canary deployment. | + +## Concerns + +| Sample | Description | +|-------------------------------------------------------|-------------------------------------------------------------------------------| +| [Authentication](./Samples/AuthenticationSample.cs) | Secures an API with API keys, roles and per-user data. | +| [CORS](./Samples/CorsSample.cs) | Allows a frontend on another origin to call the API from the browser. | +| [Error Handling](./Samples/ErrorHandlingSample.cs) | JSON errors for the API, HTML error pages for the website, custom mapping. | +| [Localization](./Samples/LocalizationSample.cs) | Responds in the language preferred by the user. | +| [Inspection](./Samples/InspectionSample.cs) | Shows what the server received and responded, to debug clients. | + +## Concepts + +| Sample | Description | +|-----------------------------------------------------------------|-----------------------------------------------------------------| +| [Dependency Injection](./Samples/DependencyInjectionSample.cs) | Lets the framework construct services and pass dependencies. | + +## Use Cases + +These samples combine multiple modules the way an application typically would. + +| Sample | Description | +|--------------------------------------------------------|-----------------------------------------------------------------------------------------------| +| [File Share](./Samples/FileShareSample.cs) | Password protected directory listing with resumable downloads. | +| [Legacy Migration](./Samples/LegacyMigrationSample.cs) | Replaces a legacy app step by step using a reverse proxy, redirects and new endpoints. | + +The [Ioxide](./Samples/Ioxide/README.md) folder contains samples for the io_uring based engine. diff --git a/Playground/Resources/Spa/app.js b/Playground/Resources/Spa/app.js new file mode 100644 index 000000000..317cfaa73 --- /dev/null +++ b/Playground/Resources/Spa/app.js @@ -0,0 +1,24 @@ +// a minimal client side router, as React Router or the Angular router would provide it +const base = document.baseURI; + +function render() { + const route = location.href.substring(base.length); + + document.getElementById('view').textContent = (route === '') + ? 'Home - reload the page on any route, the server will always deliver this application.' + : `Route "${route}" rendered in the browser.`; +} + +document.addEventListener('click', (event) => { + const link = event.target.closest('[data-route]'); + + if (link) { + event.preventDefault(); + history.pushState(null, '', link.href); + render(); + } +}); + +window.addEventListener('popstate', render); + +render(); diff --git a/Playground/Resources/Spa/index.html b/Playground/Resources/Spa/index.html new file mode 100644 index 000000000..65101fc8a --- /dev/null +++ b/Playground/Resources/Spa/index.html @@ -0,0 +1,17 @@ + + + + + Single Page Application + + + + + +
+ + + diff --git a/Playground/Resources/Website/about/index.html b/Playground/Resources/Website/about/index.html new file mode 100644 index 000000000..7b67571c3 --- /dev/null +++ b/Playground/Resources/Website/about/index.html @@ -0,0 +1,12 @@ + + + + + About + + + +

About

+

Served from about/index.html. Back

+ + diff --git a/Playground/Resources/Website/index.html b/Playground/Resources/Website/index.html new file mode 100644 index 000000000..e0713c29a --- /dev/null +++ b/Playground/Resources/Website/index.html @@ -0,0 +1,13 @@ + + + + + Static Website + + + +

Static Website

+

This page is index.html, served for the root of the website.

+

About is a folder with its own index.html.

+ + diff --git a/Playground/Resources/Website/styles.css b/Playground/Resources/Website/styles.css new file mode 100644 index 000000000..d4a62db20 --- /dev/null +++ b/Playground/Resources/Website/styles.css @@ -0,0 +1,6 @@ +body { + font-family: system-ui, sans-serif; + max-width: 40rem; + margin: 3rem auto; + line-height: 1.5; +} diff --git a/Playground/Samples/ApiDocumentationSample.cs b/Playground/Samples/ApiDocumentationSample.cs new file mode 100644 index 000000000..55e818a24 --- /dev/null +++ b/Playground/Samples/ApiDocumentationSample.cs @@ -0,0 +1,75 @@ +using GenHTTP.Api.Content; +using GenHTTP.Api.Protocol; + +using GenHTTP.Modules.ApiBrowsing; +using GenHTTP.Modules.Layouting; +using GenHTTP.Modules.OpenApi; +using GenHTTP.Modules.Reflection; +using GenHTTP.Modules.Webservices; + +namespace GenHTTP.Playground.Samples; + +public static class ApiDocumentationSample +{ + + public static IHandlerBuilder Create() + { + /* + * + * Generates an Open API definition for a web service and lets developers + * explore and try the API in their browser. The viewers are hosted by the + * server itself, so no internet connection is required. + * + * Works the same way for functional handlers and controllers. + * + * See https://genhttp.org/documentation/content/concerns/open-api/ + * and https://genhttp.org/documentation/content/handlers/api-browsing/ + * + */ + + return Layout.Create() + .AddService("books") + .AddOpenApi() // GET http://localhost:8080/api-docs/openapi.json (or .yaml) + .AddSwaggerUi() // GET http://localhost:8080/api-docs/swagger/ + .AddRedoc() // GET http://localhost:8080/api-docs/redoc/ + .AddScalar(title: "Book API"); // GET http://localhost:8080/api-docs/scalar/ + } + + public record Book(int Id, string Title); + + public class BookService + { + private static readonly List Books = + [ + new(1, "Lord of the Rings") + ]; + + [ResourceMethod] + public List List() => Books; + + [ResourceMethod(":id")] + public Book Get(int id) + => Books.FirstOrDefault(b => b.Id == id) ?? throw new ProviderException(ResponseStatus.NotFound, $"There is no book with id {id}"); + + [ResourceMethod(Method.Put)] + public Book Create(Book book) + { + var toAdd = book with + { + Id = Books.Select(b => b.Id).DefaultIfEmpty().Max() + 1 + }; + + Books.Add(toAdd); + + return toAdd; + } + + [ResourceMethod(Method.Delete, ":id")] + public void Delete(int id) + { + Books.RemoveAll(b => b.Id == id); + } + + } + +} diff --git a/Playground/Samples/AuthenticationSample.cs b/Playground/Samples/AuthenticationSample.cs new file mode 100644 index 000000000..06b4ad1e4 --- /dev/null +++ b/Playground/Samples/AuthenticationSample.cs @@ -0,0 +1,92 @@ +using GenHTTP.Api.Content; +using GenHTTP.Api.Content.Authentication; +using GenHTTP.Api.Protocol; + +using GenHTTP.Modules.Authentication; +using GenHTTP.Modules.Layouting; +using GenHTTP.Modules.Reflection; +using GenHTTP.Modules.Reflection.Injectors; +using GenHTTP.Modules.Webservices; + +namespace GenHTTP.Playground.Samples; + +public static class AuthenticationSample +{ + + public static IHandlerBuilder Create() + { + /* + * + * A notes API secured with API keys. Every user only sees their own notes, + * while administrators may see the notes of all users. + * + * Clients send their key via the "X-API-Key" header: "alice-key" for a user, + * "bob-key" for an administrator. + * + * Basic, bearer (JWT) and client certificate authentication work the same way. + * + * See https://genhttp.org/documentation/content/concerns/authentication/ + * + */ + + var auth = ApiKeyAuthentication.Create() + .Authenticator(AuthenticateAsync); + + // allows the service methods to declare the user as a parameter + var injection = Injection.Default() + .Add(new UserInjector()); + + return Layout.Create() + .AddService("notes", injectors: injection) + .Authentication(auth); + } + + private static ValueTask AuthenticateAsync(IRequest request, string key) + { + // this is where you would look up the key in your database + IUser? user = key switch + { + "alice-key" => new NoteUser("alice", "USER"), + "bob-key" => new NoteUser("bob", "USER", "ADMIN"), + _ => null // unknown key, access denied + }; + + return new(user); + } + + public record NoteUser(string Name, params string[] Roles) : IUser + { + + public string DisplayName => Name; + + } + + public record Note(string Owner, string Text); + + public class NoteService + { + private static readonly List Notes = []; + + // GET http://localhost:8080/authentication/notes/ + [ResourceMethod] + public List Mine(NoteUser user) => Notes.Where(n => n.Owner == user.Name).ToList(); + + // PUT http://localhost:8080/authentication/notes/ with the text as body + [ResourceMethod(Method.Put)] + public Note Add(NoteUser user, [FromBody] string text) + { + var note = new Note(user.Name, text); + + Notes.Add(note); + + return note; + } + + // GET http://localhost:8080/authentication/notes/all + [ResourceMethod("all")] + [RequireRole("ADMIN")] + public List All() => Notes; + + } + +} diff --git a/Playground/Samples/ControllerSample.cs b/Playground/Samples/ControllerSample.cs index e24a2ef25..9a0a0ed12 100644 --- a/Playground/Samples/ControllerSample.cs +++ b/Playground/Samples/ControllerSample.cs @@ -33,24 +33,24 @@ public class BookController new(1, "Lord of the Rings") ]; - // GET http://localhost:8080/books/ - [ControllerAction] + // GET http://localhost:8080/controllers/books/ + [ControllerAction(Method.Get)] public List Index() => Books; - // PUT http://localhost:8080/books/create with JSON/XML/... payload + // PUT http://localhost:8080/controllers/books/create/ with JSON/XML/... payload [ControllerAction(Method.Put)] public Book Create(Book book) { var toAdd = book with { - Id = Books.Max(b => b.Id) + 1 + Id = Books.Select(b => b.Id).DefaultIfEmpty().Max() + 1 }; Books.Add(toAdd); return toAdd; } - // DELETE http://localhost:8080/books/delete/1 + // DELETE http://localhost:8080/controllers/books/delete/1/ [ControllerAction(Method.Delete)] public void Delete([FromPath] int id) { diff --git a/Playground/Samples/CorsSample.cs b/Playground/Samples/CorsSample.cs new file mode 100644 index 000000000..d1e49668b --- /dev/null +++ b/Playground/Samples/CorsSample.cs @@ -0,0 +1,39 @@ +using GenHTTP.Api.Content; +using GenHTTP.Api.Protocol; + +using GenHTTP.Modules.Functional; +using GenHTTP.Modules.Layouting; +using GenHTTP.Modules.Security; + +namespace GenHTTP.Playground.Samples; + +public static class CorsSample +{ + + public static IHandlerBuilder Create() + { + /* + * + * Allows a frontend hosted on another origin (e.g. a React app served by + * the Vite dev server on http://localhost:5173) to call this API from the browser. + * Browsers will block requests from any other origin. + * + * See https://genhttp.org/documentation/content/concerns/cors/ + * + */ + + var todos = new List { "Write the frontend" }; + + var api = Inline.Create() + .Get(() => todos) // GET http://localhost:8080/cors/api/todos/ + .Put((string todo) => todos.Add(todo)); // PUT http://localhost:8080/cors/api/todos/?todo=... + + var policy = CorsPolicy.Restrictive() + .Add("http://localhost:5173", [RequestMethod.Get, RequestMethod.Put], allowedHeaders: null, exposedHeaders: null, allowCredentials: false); + + return Layout.Create() + .Add("api/todos", api) + .Add(policy); + } + +} diff --git a/Playground/Samples/CustomFrameworkSample.cs b/Playground/Samples/CustomFrameworkSample.cs index 992af6c1e..9da5b6b86 100644 --- a/Playground/Samples/CustomFrameworkSample.cs +++ b/Playground/Samples/CustomFrameworkSample.cs @@ -26,9 +26,9 @@ public static IHandlerBuilder Create() */ return Layout.Create() - .Add(new CustomFrameworkHandler()) + .Add(new CustomFrameworkHandler()) // GET http://localhost:8080/custom-framework/42 .AddOpenApi() - .AddScalar(); + .AddScalar(); // GET http://localhost:8080/custom-framework/scalar/ } public class CustomFrameworkHandler : IHandler, IServiceMethodProvider diff --git a/Playground/Samples/DependencyInjectionSample.cs b/Playground/Samples/DependencyInjectionSample.cs new file mode 100644 index 000000000..659573228 --- /dev/null +++ b/Playground/Samples/DependencyInjectionSample.cs @@ -0,0 +1,99 @@ +using GenHTTP.Api.Content; + +using GenHTTP.Modules.DependencyInjection; +using GenHTTP.Modules.Layouting; +using GenHTTP.Modules.Reflection; +using GenHTTP.Modules.Webservices; + +using Microsoft.Extensions.DependencyInjection; + +namespace GenHTTP.Playground.Samples; + +public static class DependencyInjectionSample +{ + + public static IHandlerBuilder Create() + { + /* + * + * Lets the framework create services and pass their dependencies, so the + * services do not need to know how to construct them (and can be tested + * with fakes). + * + * Dependency injection needs to be enabled on the host, see Services() below + * and Program.cs: + * + * Host.Create() + * .AddDependencyInjection(DependencyInjectionSample.Services()) + * + * See https://genhttp.org/documentation/content/concepts/dependency-injection/ + * + */ + + return Layout.Create() + .AddDependentService("books"); // GET http://localhost:8080/dependency-injection/books/ + } + + public static IServiceProvider Services() + { + var services = new ServiceCollection(); + + services.AddSingleton() + .AddSingleton(TimeProvider.System); + + return services.BuildServiceProvider(); + } + + public record Book(int Id, string Title, DateTimeOffset? Added = null); + + public interface IBookRepository + { + + List GetAll(); + + Book Add(Book book); + + } + + public class InMemoryBookRepository : IBookRepository + { + private readonly List _books = [new(1, "Lord of the Rings")]; + + private readonly Lock _sync = new(); + + public List GetAll() + { + lock (_sync) + { + return [.._books]; + } + } + + public Book Add(Book book) + { + lock (_sync) + { + var toAdd = book with { Id = _books.Select(b => b.Id).DefaultIfEmpty().Max() + 1 }; + + _books.Add(toAdd); + + return toAdd; + } + } + + } + + // dependencies can be injected via the constructor ... + public class BookService(IBookRepository repository) + { + + [ResourceMethod] + public List List() => repository.GetAll(); + + // ... or as a method parameter + [ResourceMethod(Method.Put)] + public Book Add(Book book, TimeProvider time) => repository.Add(book with { Added = time.GetUtcNow() }); + + } + +} diff --git a/Playground/Samples/ErrorHandlingSample.cs b/Playground/Samples/ErrorHandlingSample.cs new file mode 100644 index 000000000..5e92fc171 --- /dev/null +++ b/Playground/Samples/ErrorHandlingSample.cs @@ -0,0 +1,77 @@ +using GenHTTP.Api.Content; +using GenHTTP.Api.Protocol; + +using GenHTTP.Modules.ErrorHandling; +using GenHTTP.Modules.Functional; +using GenHTTP.Modules.IO; +using GenHTTP.Modules.Layouting; + +namespace GenHTTP.Playground.Samples; + +public static class ErrorHandlingSample +{ + + public static IHandlerBuilder Create() + { + /* + * + * A shop with a website for humans and an API for machines. Errors in the API + * are reported as JSON (or XML, ... as requested by the client), while the website + * renders HTML error pages. Exceptions thrown by the business logic are mapped + * to HTTP status codes without the business logic knowing about HTTP. + * + * See https://genhttp.org/documentation/content/concerns/error-handling/ + * + */ + + var orders = Inline.Create() + // GET http://localhost:8080/errors/api/orders/42 (404 as JSON) + .Get(":id", (int id) => (id == 1) ? new Order(1, "Coffee") : throw new ProviderException(ResponseStatus.NotFound, $"There is no order with id {id}")) + // POST http://localhost:8080/errors/api/orders/ (409 via the custom mapper) + .Post((Order order) => Shop.PlaceOrder(order)) + .Add(ErrorHandler.From(new OutOfStockMapper())); + + var website = Layout.Create() + .Index(Content.From(Resource.FromString("

Welcome to our shop!

").Type(ContentType.TextHtml))) + .Add(ErrorHandler.Html()); + + return Layout.Create() + .Add("api/orders", orders) + .Add(website); // e.g. GET http://localhost:8080/errors/does-not-exist (404 as HTML page) + } + + public record Order(int Id, string Product); + + public class OutOfStockException(string product) : Exception($"Sorry, '{product}' is sold out") + { + + public string Product => product; + + } + + public static class Shop + { + + public static Order PlaceOrder(Order order) => throw new OutOfStockException(order.Product); + + } + + public class OutOfStockMapper : IErrorMapper + { + + public ValueTask Map(IRequest request, IHandler handler, OutOfStockException error, ByteString? acceptedFormat) + { + var response = request.Respond() + .Status(ResponseStatus.Conflict) + .Content(error.Message, ContentType.TextPlain) + .Build(); + + return new(response); + } + + // null passes the request on, so the default error handling renders the 404 + public ValueTask GetNotFound(IRequest request, IHandler handler, ByteString? acceptedFormat) => new(); + + } + +} diff --git a/Playground/Samples/FileShareSample.cs b/Playground/Samples/FileShareSample.cs new file mode 100644 index 000000000..202446a06 --- /dev/null +++ b/Playground/Samples/FileShareSample.cs @@ -0,0 +1,37 @@ +using GenHTTP.Api.Content; + +using GenHTTP.Modules.Authentication; +using GenHTTP.Modules.DirectoryBrowsing; +using GenHTTP.Modules.IO; + +namespace GenHTTP.Playground.Samples; + +public static class FileShareSample +{ + + public static IHandlerBuilder Create() + { + /* + * + * Shares a folder with friends: they log in with their browser, browse + * through the files and download them. Downloads of large files can be + * paused and resumed, as range requests are supported. + * + * Open http://localhost:8080/file-share/ and log in as "friend" / "secret". + * + * See https://genhttp.org/documentation/content/handlers/listing/ + * and https://genhttp.org/documentation/content/concerns/range-support/ + * + */ + + var files = ResourceTree.FromDirectory("./"); + + var auth = BasicAuthentication.Create() + .Add("friend", "secret"); + + return Listing.From(files) + .AddRangeSupport() + .Authentication(auth); + } + +} diff --git a/Playground/Samples/FunctionalSample.cs b/Playground/Samples/FunctionalSample.cs index f4f6463c4..636d14dc4 100644 --- a/Playground/Samples/FunctionalSample.cs +++ b/Playground/Samples/FunctionalSample.cs @@ -25,18 +25,18 @@ public static IHandlerBuilder Create() }; var service = Inline.Create() - .Get(() => books) // GET http://localhost:8080/books/ - .Put((Book book) => // PUT http://localhost:8080/books/ with JSON/XML/... payload + .Get(() => books) // GET http://localhost:8080/functional/books/ + .Put((Book book) => // PUT http://localhost:8080/functional/books/ with JSON/XML/... payload { var toAdd = book with { - Id = books.Max(b => b.Id) + 1 + Id = books.Select(b => b.Id).DefaultIfEmpty().Max() + 1 }; books.Add(toAdd); return toAdd; }) - .Delete(":id", (int id) => books.RemoveAll(b => b.Id == id)); // DELETE http://localhost:8080/books/1 + .Delete(":id", (int id) => books.RemoveAll(b => b.Id == id)); // DELETE http://localhost:8080/functional/books/1 return Layout.Create() .Add("books", service); diff --git a/Playground/Samples/InspectionSample.cs b/Playground/Samples/InspectionSample.cs new file mode 100644 index 000000000..bbc91e7df --- /dev/null +++ b/Playground/Samples/InspectionSample.cs @@ -0,0 +1,36 @@ +using GenHTTP.Api.Content; + +using GenHTTP.Modules.Functional; +using GenHTTP.Modules.Inspection; +using GenHTTP.Modules.Layouting; + +namespace GenHTTP.Playground.Samples; + +public static class InspectionSample +{ + + public static IHandlerBuilder Create() + { + /* + * + * Helps to find out why a client receives a certain response. Append "?inspect" + * to any URL to see the request as the server received it, together with + * the response the server would have sent. + * + * As this exposes details about your server, only add it while developing. + * + * See https://genhttp.org/documentation/content/concerns/inspection/ + * + */ + + var orders = Inline.Create() + .Get((int limit) => Enumerable.Range(1, limit).Select(i => new Order(i))); + + return Layout.Create() + .Add("api/orders", orders) // GET http://localhost:8080/inspection/api/orders/?limit=5&inspect + .AddInspector(); + } + + public record Order(int Id); + +} diff --git a/Playground/Samples/LayoutingSample.cs b/Playground/Samples/LayoutingSample.cs index dd03f9c3e..cf5b7b54e 100644 --- a/Playground/Samples/LayoutingSample.cs +++ b/Playground/Samples/LayoutingSample.cs @@ -31,8 +31,8 @@ public static IHandlerBuilder Create() // assemble our application from the parts above and // register them at the given URLs return Layout.Create() - .Add("assets", assets) // e.g. GET http://localhost:8080/assets/GenHTTP.Playground.xml - .Add("api", api); // e.g. GET http://localhost:8080/api/ + .Add("assets", assets) // e.g. GET http://localhost:8080/layouting/assets/README.md + .Add("api", api); // e.g. GET http://localhost:8080/layouting/api/ } } diff --git a/Playground/Samples/LegacyMigrationSample.cs b/Playground/Samples/LegacyMigrationSample.cs new file mode 100644 index 000000000..96456e4cf --- /dev/null +++ b/Playground/Samples/LegacyMigrationSample.cs @@ -0,0 +1,49 @@ +using GenHTTP.Api.Content; +using GenHTTP.Api.Protocol; + +using GenHTTP.Modules.Functional; +using GenHTTP.Modules.IO; +using GenHTTP.Modules.Layouting; +using GenHTTP.Modules.Redirects; +using GenHTTP.Modules.ReverseProxy; + +namespace GenHTTP.Playground.Samples; + +public static class LegacyMigrationSample +{ + + public static IHandlerBuilder Create() + { + /* + * + * Replaces a legacy web application step by step: GenHTTP sits in front of + * the old application and serves the parts that have already been rewritten. + * Moved pages are redirected, everything else is still served by the legacy + * application (expected to run on http://localhost:5000). + * + * See https://genhttp.org/documentation/content/handlers/reverse-proxy/ + * and https://genhttp.org/documentation/content/handlers/redirects/ + * + */ + + var newApi = Inline.Create() + .Get("status", () => new Status(true)); + + var contact = Content.From(Resource.FromString("

Contact us

").Type(ContentType.TextHtml)); + + var legacy = Proxy.Create() + .Upstream("http://localhost:5000/") + .ConnectTimeout(TimeSpan.FromSeconds(5)) + .ReadTimeout(TimeSpan.FromSeconds(30)); + + return Layout.Create() + .Add("api/v2", newApi) // GET http://localhost:8080/legacy-migration/api/v2/status + .Add("contact", contact) + .Add("contact.php", Redirect.To("/legacy-migration/contact")) // permanent, so search engines learn the new URL + .Add("shop", Redirect.To("https://shop.example.com/", temporary: true)) + .Add(legacy); // everything else, e.g. GET http://localhost:8080/legacy-migration/login.php + } + + public record Status(bool Healthy); + +} diff --git a/Playground/Samples/LoadBalancerSample.cs b/Playground/Samples/LoadBalancerSample.cs new file mode 100644 index 000000000..e6fe6f821 --- /dev/null +++ b/Playground/Samples/LoadBalancerSample.cs @@ -0,0 +1,44 @@ +using GenHTTP.Api.Content; +using GenHTTP.Api.Infrastructure; +using GenHTTP.Api.Protocol; + +using GenHTTP.Modules.Layouting; +using GenHTTP.Modules.LoadBalancing; + +namespace GenHTTP.Playground.Samples; + +public static class LoadBalancerSample +{ + + private static readonly ByteString CanaryHeader = new("X-Canary"); + + public static IHandlerBuilder Create() + { + /* + * + * Distributes API requests over multiple worker processes (expected to run + * on http://localhost:5001 and :5002) and sends clients downloading files + * to one of the mirror servers. + * + * Clients sending an "X-Canary" header are served by a canary worker + * (on http://localhost:5003), so a new version can be tested with real traffic. + * + * See https://genhttp.org/documentation/content/handlers/load-balancer/ + * + */ + + var workers = LoadBalancer.Create() + .Proxy("http://localhost:5001/") + .Proxy("http://localhost:5002/") + .Proxy("http://localhost:5003/", r => r.Header.Headers.ContainsKey(CanaryHeader) ? Priority.High : Priority.Low); + + var mirrors = LoadBalancer.Create() + .Redirect("https://mirror1.example.com/") + .Redirect("https://mirror2.example.com/"); + + return Layout.Create() + .Add("api", workers) // GET http://localhost:8080/load-balancing/api/ + .Add("downloads", mirrors); // GET http://localhost:8080/load-balancing/downloads/setup.exe + } + +} diff --git a/Playground/Samples/LocalizationSample.cs b/Playground/Samples/LocalizationSample.cs new file mode 100644 index 000000000..1cc99be76 --- /dev/null +++ b/Playground/Samples/LocalizationSample.cs @@ -0,0 +1,53 @@ +using System.Globalization; + +using GenHTTP.Api.Content; + +using GenHTTP.Modules.Functional; +using GenHTTP.Modules.I18n; +using GenHTTP.Modules.Layouting; + +namespace GenHTTP.Playground.Samples; + +public static class LocalizationSample +{ + + public static IHandlerBuilder Create() + { + /* + * + * Greets users in their preferred language and formats dates the way + * they are used to. The language is taken from the "lang" query parameter + * or the Accept-Language header sent by the browser. + * + * See https://genhttp.org/documentation/content/concerns/localization/ + * + */ + + var greetings = new Dictionary + { + ["en"] = "Hello", + ["de"] = "Hallo", + ["fr"] = "Bonjour" + }; + + var greeting = Inline.Create() + .Get(() => + { + var culture = CultureInfo.CurrentCulture; + + return $"{greetings[culture.TwoLetterISOLanguageName]}! {DateTime.Now.ToString("D", culture)}"; + }); + + var localization = Localization.Create() + .FromQuery("lang") + .FromHeader() + .Supports(culture => greetings.ContainsKey(culture.TwoLetterISOLanguageName)) // accepts regional variants such as de-CH + .Default(CultureInfo.GetCultureInfo("en")) + .Setter(currentCulture: true, currentUiCulture: true); + + return Layout.Create() + .Add("greeting", greeting) // GET http://localhost:8080/localization/greeting/?lang=fr + .Add(localization); + } + +} diff --git a/Playground/Samples/McpSample.cs b/Playground/Samples/McpSample.cs index cf57b28e5..fabb8a4fa 100644 --- a/Playground/Samples/McpSample.cs +++ b/Playground/Samples/McpSample.cs @@ -4,7 +4,6 @@ using GenHTTP.Api.Content.Documentation; using GenHTTP.Api.Protocol; -using GenHTTP.Modules.Layouting; using GenHTTP.Modules.Mcp; namespace GenHTTP.Playground.Samples; @@ -29,14 +28,11 @@ public static IHandlerBuilder Create() * */ - var tools = Tools.Create() - .Server("library", "1.0.0", "Library") - .Instructions("Search for books before lending them to a reader.") - .Add() - .Add("get_time", "Returns the current time of the library (UTC)", [Tool(ReadOnly = true)] () => DateTime.UtcNow); - - return Layout.Create() - .Add("mcp", tools); + return Tools.Create() + .Server("library", "1.0.0", "Library") + .Instructions("Search for books before lending them to a reader.") + .Add() + .Add("get_time", "Returns the current time of the library (UTC)", [Tool(ReadOnly = true)] () => DateTime.UtcNow); } public record Book(int Id, string Title, string? LentTo); diff --git a/Playground/Samples/PagesSample.cs b/Playground/Samples/PagesSample.cs new file mode 100644 index 000000000..43931358c --- /dev/null +++ b/Playground/Samples/PagesSample.cs @@ -0,0 +1,82 @@ +using Cottle; + +using GenHTTP.Api.Content; +using GenHTTP.Api.Protocol; + +using GenHTTP.Modules.Functional; +using GenHTTP.Modules.IO; +using GenHTTP.Modules.Layouting; +using GenHTTP.Modules.Pages; + +namespace GenHTTP.Playground.Samples; + +public static class PagesSample +{ + + public static IHandlerBuilder Create() + { + /* + * + * Renders simple HTML pages on the server, e.g. for an internal admin + * tool that does not justify a frontend framework. + * + * Templates are usually embedded into the assembly and loaded via + * Resource.FromAssembly("Books.html"). + * + * See https://genhttp.org/documentation/content/handlers/pages/ + * + */ + + var template = Renderer.From(Resource.FromString(BooksTemplate).Build()); + + var books = Inline.Create() + .Get(async (IRequest request) => + { + var model = new Dictionary + { + ["books"] = Value.FromEnumerable(Books.Select(b => Value.FromDictionary(new Dictionary + { + ["id"] = b.Id, + ["title"] = b.Title.Escaped() // the template engine does not escape HTML for you + }))) + }; + + return request.GetPage(await template.RenderAsync(model)); + }); + + var about = Inline.Create() + .Get(async (IRequest request) => request.GetPage(await Renderer.Server.RenderAsync("About", "

This library runs on GenHTTP.

"))); + + return Layout.Create() + .Add("books", books) // GET http://localhost:8080/pages/books/ (rendered from a Cottle template) + .Add("about", about); // GET http://localhost:8080/pages/about/ (in the style of the server's own pages) + } + + public record Book(int Id, string Title); + + private static readonly List Books = + [ + new(1, "Lord of the Rings"), + new(2, "Pride & Prejudice") + ]; + + private const string BooksTemplate = + """ + + + + + Books + + + + + {for book in books: + + } +
IDTitle
{book.id}{book.title}
+ + + """; + +} diff --git a/Playground/Samples/ServerSentEventsSample.cs b/Playground/Samples/ServerSentEventsSample.cs new file mode 100644 index 000000000..97a11beb0 --- /dev/null +++ b/Playground/Samples/ServerSentEventsSample.cs @@ -0,0 +1,88 @@ +using System.Diagnostics; + +using GenHTTP.Api.Content; +using GenHTTP.Api.Protocol; + +using GenHTTP.Modules.IO; +using GenHTTP.Modules.Layouting; +using GenHTTP.Modules.ServerSentEvents; + +namespace GenHTTP.Playground.Samples; + +public static class ServerSentEventsSample +{ + + public static IHandlerBuilder Create() + { + /* + * + * A live dashboard: the server pushes its current memory usage to + * the browser every second, without the client polling for it. + * + * See https://genhttp.org/documentation/content/handlers/server-sent-events/ + * + */ + + var stats = EventSource.Create() + .Generator(SendStatsAsync); + + var client = Content.From(Resource.FromString(ClientPage).Type(ContentType.TextHtml)); + + return Layout.Create() + .Index(client) // GET http://localhost:8080/sse/ + .Add("stats", stats); // GET http://localhost:8080/sse/stats/ + } + + public record ServerStats(long WorkingSet, long ManagedMemory, int Collections); + + private static async ValueTask SendStatsAsync(IEventConnection connection) + { + var id = 0; + + while (connection.Connected) + { + using var process = Process.GetCurrentProcess(); + + var stats = new ServerStats(process.WorkingSet64, GC.GetTotalMemory(false), GC.CollectionCount(0)); + + // serialized to JSON, the browser listens for the "stats" event type + await connection.DataAsync(stats, eventType: "stats", eventId: $"{id++}"); + + await Task.Delay(1000); + } + } + + private const string ClientPage = + """ + + + + + Server Stats + + +

Server Stats

+
+
Working set
-
+
Managed memory
-
+
Gen 0 collections
-
+
+ + + + """; + +} diff --git a/Playground/Samples/SinglePageApplicationSample.cs b/Playground/Samples/SinglePageApplicationSample.cs index e0163ca48..a3aeb0775 100644 --- a/Playground/Samples/SinglePageApplicationSample.cs +++ b/Playground/Samples/SinglePageApplicationSample.cs @@ -18,9 +18,12 @@ public static IHandlerBuilder Create() * */ - var files = ResourceTree.FromDirectory("/var/app"); + // embedded into the assembly here, use ResourceTree.FromDirectory("/var/app") to serve your build output + var files = ResourceTree.FromAssembly("Resources.Spa"); - return SinglePageApplication.From(files); + // GET http://localhost:8080/spa/books/42 serves index.html, the route is rendered in the browser + return SinglePageApplication.From(files) + .ServerSideRouting(); } } diff --git a/Playground/Samples/StaticFileSample.cs b/Playground/Samples/StaticFileSample.cs index 2e30d43e6..acc2e5f15 100644 --- a/Playground/Samples/StaticFileSample.cs +++ b/Playground/Samples/StaticFileSample.cs @@ -13,11 +13,11 @@ public static IHandlerBuilder Create() * * Serves files from a given directory or resource tree. * - * See https://genhttp.org/documentation/content/handlers/static-content/ + * See https://genhttp.org/documentation/content/handlers/files/ * */ - // e.g. GET http://localhost:8080/assets/GenHTTP.Playground.xml + // e.g. GET http://localhost:8080/static-files/README.md return Assets.From("./"); } diff --git a/Playground/Samples/StaticWebsiteSample.cs b/Playground/Samples/StaticWebsiteSample.cs index 7b2f88a5a..da3dd4723 100644 --- a/Playground/Samples/StaticWebsiteSample.cs +++ b/Playground/Samples/StaticWebsiteSample.cs @@ -18,8 +18,10 @@ public static IHandlerBuilder Create() * */ - var files = ResourceTree.FromDirectory("/var/www"); + // embedded into the assembly here, use ResourceTree.FromDirectory("/var/www") to serve a folder + var files = ResourceTree.FromAssembly("Resources.Website"); + // GET http://localhost:8080/static-website/ serves index.html return StaticWebsite.From(files); } diff --git a/Playground/Samples/VirtualHostingSample.cs b/Playground/Samples/VirtualHostingSample.cs new file mode 100644 index 000000000..c9065c793 --- /dev/null +++ b/Playground/Samples/VirtualHostingSample.cs @@ -0,0 +1,38 @@ +using GenHTTP.Api.Content; +using GenHTTP.Api.Protocol; + +using GenHTTP.Modules.IO; +using GenHTTP.Modules.Redirects; +using GenHTTP.Modules.VirtualHosting; + +namespace GenHTTP.Playground.Samples; + +public static class VirtualHostingSample +{ + + public static IHandlerBuilder Create() + { + /* + * + * Hosts multiple websites on a single server, one per domain. Browsers + * resolve *.localhost to your machine, so you can try this locally: + * + * http://blog.localhost:8080/virtual-hosting/ + * http://shop.localhost:8080/virtual-hosting/ + * http://localhost:8080/virtual-hosting/ (redirects to the blog) + * + * See https://genhttp.org/documentation/content/handlers/virtual-hosts/ + * + */ + + var blog = Content.From(Resource.FromString("

My Blog

").Type(ContentType.TextHtml)); + + var shop = Content.From(Resource.FromString("

My Shop

").Type(ContentType.TextHtml)); + + return VirtualHosts.Create() + .Add("blog.localhost", blog) + .Add("shop.localhost", shop) + .Default(Redirect.To("http://blog.localhost:8080/virtual-hosting/", temporary: true)); // any other host + } + +} diff --git a/Playground/Samples/WebserviceSample.cs b/Playground/Samples/WebserviceSample.cs index 613824142..338f6279a 100644 --- a/Playground/Samples/WebserviceSample.cs +++ b/Playground/Samples/WebserviceSample.cs @@ -34,17 +34,17 @@ public class BookService new(1, "Lord of the Rings") ]; - // GET http://localhost:8080/books/ + // GET http://localhost:8080/webservices/books/ [ResourceMethod] public List List() => Books; - // PUT http://localhost:8080/books/ with JSON/XML/... payload + // PUT http://localhost:8080/webservices/books/ with JSON/XML/... payload [ResourceMethod(Method.Put)] public Book Create(Book book) { var toAdd = book with { - Id = Books.Max(b => b.Id) + 1 + Id = Books.Select(b => b.Id).DefaultIfEmpty().Max() + 1 }; Books.Add(toAdd); @@ -52,7 +52,7 @@ public Book Create(Book book) return toAdd; } - // DELETE http://localhost:8080/books/1 + // DELETE http://localhost:8080/webservices/books/1 [ResourceMethod(Method.Delete, ":id")] public void Delete([FromPath] int id) { diff --git a/Playground/Samples/WebsocketSample.cs b/Playground/Samples/WebsocketSample.cs new file mode 100644 index 000000000..12c38e2c9 --- /dev/null +++ b/Playground/Samples/WebsocketSample.cs @@ -0,0 +1,143 @@ +using GenHTTP.Api.Content; +using GenHTTP.Api.Protocol; + +using GenHTTP.Modules.IO; +using GenHTTP.Modules.Layouting; + +namespace GenHTTP.Playground.Samples; + +// imported here as the Websocket.Client package (referenced by the test project) declares a root namespace named "Websocket" +using GenHTTP.Modules.Websockets; + +public static class WebsocketSample +{ + + public static IHandlerBuilder Create() + { + /* + * + * A chat room: every message a client sends over the websocket is + * pushed to all connected clients. + * + * Open http://localhost:8080/websockets/ in two browser windows and start chatting. + * + * See https://genhttp.org/documentation/content/frameworks/websockets/ + * + */ + + var chat = Websocket.Reactive() + .Handler(new ChatHandler()); + + var client = Content.From(Resource.FromString(ClientPage).Type(ContentType.TextHtml)); + + return Layout.Create() + .Index(client) // GET http://localhost:8080/websockets/ + .Add("chat", chat); // ws://localhost:8080/websockets/chat + } + + public record ChatMessage(string Author, string Text, DateTime? Sent = null); + + public class ChatHandler : IReactiveHandler + { + private readonly List _clients = []; + + // connections are not thread-safe, so we never write to them concurrently + private readonly SemaphoreSlim _sync = new(1, 1); + + public async ValueTask OnConnected(IReactiveConnection connection) + { + await _sync.WaitAsync(); + + try + { + _clients.Add(connection); + } + finally + { + _sync.Release(); + } + } + + public async ValueTask OnMessage(IReactiveConnection connection, IWebsocketFrame message) + { + // JSON sent by the client is deserialized into our record + var received = await message.ReadPayloadAsync(); + + var toSend = received with { Sent = DateTime.UtcNow }; + + await _sync.WaitAsync(); + + try + { + foreach (var client in _clients) + { + // ... and serialized to JSON again + await client.WritePayloadAsync(toSend); + } + } + finally + { + _sync.Release(); + } + } + + public async ValueTask OnClose(IReactiveConnection connection, IWebsocketFrame message) + { + await _sync.WaitAsync(); + + try + { + _clients.Remove(connection); + } + finally + { + _sync.Release(); + } + + await connection.CloseAsync(); + } + + } + + private const string ClientPage = + """ + + + + + Chat + + +
+ + + +
+
    + + + + """; + +} From d2ccf1e9ebfd905c2de49f41ab66e7ce7e3b232c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andreas=20N=C3=A4geli?= Date: Wed, 11 Nov 2026 16:11:03 +0100 Subject: [PATCH 2/4] chore(playground): Move the samples to the website The samples now live at https://genhttp.org/playground/, where they can be read and called live. The playground is back to a minimal app for manual checks; the Ioxide samples stay, as the website does not cover them. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016Z4d2Q4o4JhUDoAL6Zkxe9 --- AGENTS.md | 4 +- Playground/Browser/Catalog.cs | 161 --- Playground/Browser/Index.html | 987 ------------------ Playground/Browser/Sample.cs | 30 - Playground/Browser/SampleBrowser.cs | 43 - Playground/GenHTTP.Playground.csproj | 19 +- Playground/Program.cs | 19 +- Playground/README.md | 63 +- Playground/Resources/Spa/app.js | 24 - Playground/Resources/Spa/index.html | 17 - Playground/Resources/Website/about/index.html | 12 - Playground/Resources/Website/index.html | 13 - Playground/Resources/Website/styles.css | 6 - Playground/Samples/ApiDocumentationSample.cs | 75 -- Playground/Samples/AuthenticationSample.cs | 92 -- Playground/Samples/ControllerSample.cs | 62 -- Playground/Samples/CorsSample.cs | 39 - Playground/Samples/CustomFrameworkSample.cs | 81 -- .../Samples/DependencyInjectionSample.cs | 99 -- Playground/Samples/ErrorHandlingSample.cs | 77 -- Playground/Samples/FileShareSample.cs | 37 - Playground/Samples/FunctionalSample.cs | 47 - Playground/Samples/InspectionSample.cs | 36 - Playground/Samples/LayoutingSample.cs | 38 - Playground/Samples/LegacyMigrationSample.cs | 49 - Playground/Samples/LoadBalancerSample.cs | 44 - Playground/Samples/LocalizationSample.cs | 53 - Playground/Samples/McpSample.cs | 74 -- Playground/Samples/PagesSample.cs | 82 -- Playground/Samples/ServerSentEventsSample.cs | 88 -- .../Samples/SinglePageApplicationSample.cs | 30 - Playground/Samples/StaticFileSample.cs | 24 - Playground/Samples/StaticWebsiteSample.cs | 29 - Playground/Samples/VirtualHostingSample.cs | 38 - Playground/Samples/WebserviceSample.cs | 64 -- Playground/Samples/WebsocketSample.cs | 143 --- README.md | 4 +- 37 files changed, 15 insertions(+), 2788 deletions(-) delete mode 100644 Playground/Browser/Catalog.cs delete mode 100644 Playground/Browser/Index.html delete mode 100644 Playground/Browser/Sample.cs delete mode 100644 Playground/Browser/SampleBrowser.cs delete mode 100644 Playground/Resources/Spa/app.js delete mode 100644 Playground/Resources/Spa/index.html delete mode 100644 Playground/Resources/Website/about/index.html delete mode 100644 Playground/Resources/Website/index.html delete mode 100644 Playground/Resources/Website/styles.css delete mode 100644 Playground/Samples/ApiDocumentationSample.cs delete mode 100644 Playground/Samples/AuthenticationSample.cs delete mode 100644 Playground/Samples/ControllerSample.cs delete mode 100644 Playground/Samples/CorsSample.cs delete mode 100644 Playground/Samples/CustomFrameworkSample.cs delete mode 100644 Playground/Samples/DependencyInjectionSample.cs delete mode 100644 Playground/Samples/ErrorHandlingSample.cs delete mode 100644 Playground/Samples/FileShareSample.cs delete mode 100644 Playground/Samples/FunctionalSample.cs delete mode 100644 Playground/Samples/InspectionSample.cs delete mode 100644 Playground/Samples/LayoutingSample.cs delete mode 100644 Playground/Samples/LegacyMigrationSample.cs delete mode 100644 Playground/Samples/LoadBalancerSample.cs delete mode 100644 Playground/Samples/LocalizationSample.cs delete mode 100644 Playground/Samples/McpSample.cs delete mode 100644 Playground/Samples/PagesSample.cs delete mode 100644 Playground/Samples/ServerSentEventsSample.cs delete mode 100644 Playground/Samples/SinglePageApplicationSample.cs delete mode 100644 Playground/Samples/StaticFileSample.cs delete mode 100644 Playground/Samples/StaticWebsiteSample.cs delete mode 100644 Playground/Samples/VirtualHostingSample.cs delete mode 100644 Playground/Samples/WebserviceSample.cs delete mode 100644 Playground/Samples/WebsocketSample.cs diff --git a/AGENTS.md b/AGENTS.md index e39252f26..b3627b30f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -22,7 +22,7 @@ dotnet test Testing/Acceptance/GenHTTP.Testing.Acceptance.csproj -f net11.0 \ # Only one engine (Internal | Kestrel | Ioxide) TEST_ENGINE=Internal dotnet test Testing/Acceptance/GenHTTP.Testing.Acceptance.csproj -f net11.0 -cd Playground && dotnet run # sample server on http://localhost:8080 +cd Playground && dotnet run # minimal app on http://localhost:8080 ``` - Filter with `FullyQualifiedName~...`. `ClassName=Foo` silently matches nothing. @@ -49,7 +49,7 @@ cd Playground && dotnet run # sample server on ht | `Testing/Acceptance` | The test suite. Folder structure mirrors `API/`, `Engine/`, `Modules/`, `Adapters/`. | | `Benchmarks/` | BenchmarkDotNet micro-benchmarks. | | `Packages/` | Meta-package `.nuspec` files (`GenHTTP.Core`, `GenHTTP.Full`, and per-engine variants). | -| `Playground/` | Runnable samples for manual checks and for users to understand the API. | +| `Playground/` | A minimal app for manual checks. The samples for users are on the website (genhttp.org/playground). | The parser (Glyph11) and ioxide are separate projects consumed as NuGet packages. If they are checked out next to this repository (`../Glyph11`, `../ioxide`), read their source rather than guessing. Flag diff --git a/Playground/Browser/Catalog.cs b/Playground/Browser/Catalog.cs deleted file mode 100644 index 71fe4eab0..000000000 --- a/Playground/Browser/Catalog.cs +++ /dev/null @@ -1,161 +0,0 @@ -using GenHTTP.Playground.Samples; - -namespace GenHTTP.Playground.Browser; - -/// -/// All samples served by the playground, with the requests the -/// sample browser offers to try them. -/// -internal static class Catalog -{ - private const string Docs = "https://genhttp.org/documentation/content/"; - - private static readonly Dictionary Json = new() { ["Content-Type"] = "application/json" }; - - internal static readonly List Samples = - [ - // Frameworks - - new("webservices", "Frameworks", "Webservices", "Implements a REST webservice via a handler class.", - Docs + "frameworks/webservices/", "WebserviceSample.cs", WebserviceSample.Create(), - Example.Request("List all books", "GET", "/webservices/books/"), - Example.Request("Add a book", "PUT", "/webservices/books/", """{ "title": "The Hobbit" }""", Json), - Example.Request("Delete a book", "DELETE", "/webservices/books/1")), - - new("functional", "Frameworks", "Functional", "Uses delegates to implement a web service (similar to ASP.NET Core Minimal API).", - Docs + "frameworks/functional/", "FunctionalSample.cs", FunctionalSample.Create(), - Example.Request("List all books", "GET", "/functional/books/"), - Example.Request("Add a book", "PUT", "/functional/books/", """{ "title": "The Hobbit" }""", Json), - Example.Request("Delete a book", "DELETE", "/functional/books/1")), - - new("controllers", "Frameworks", "Controllers", "Uses controllers to implement a web service (similar to ASP.NET Core MVC).", - Docs + "frameworks/controllers/", "ControllerSample.cs", ControllerSample.Create(), - Example.Request("List all books", "GET", "/controllers/books/"), - Example.Request("Add a book", "PUT", "/controllers/books/create/", """{ "title": "The Hobbit" }""", Json), - Example.Request("Delete a book", "DELETE", "/controllers/books/delete/1/")), - - new("websockets", "Frameworks", "Websockets", "A chat room that pushes messages to all connected browsers.", - Docs + "frameworks/websockets/", "WebsocketSample.cs", WebsocketSample.Create(), - Example.Page("Open the chat", "/websockets/", "Open it twice to chat with yourself.")), - - new("mcp", "Frameworks", "MCP Tools", "Provides tools to AI agents such as Claude via the Model Context Protocol.", - Docs + "frameworks/mcp/", "McpSample.cs", McpSample.Create(), - Example.Shell("Add the server to Claude Code", "claude mcp add --transport http library {origin}/mcp", - "Then ask Claude \"Which books about Rome are in the library?\""), - Example.Request("List the tools, as an agent would", "POST", "/mcp/", """{ "jsonrpc": "2.0", "id": 1, "method": "tools/list" }""", Json), - Example.Request("Call a tool", "POST", "/mcp/", """{ "jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": { "name": "find_books", "arguments": { "query": "Rome" } } }""", Json)), - - new("static-website", "Frameworks", "Static Websites", "Hosts a static website (with index.html support).", - Docs + "frameworks/static-websites/", "StaticWebsiteSample.cs", StaticWebsiteSample.Create(), - Example.Page("Open the website", "/static-website/")), - - new("spa", "Frameworks", "Single Page Applications", "Hosts a SPA such as a React or Angular application.", - Docs + "frameworks/single-page-applications/", "SinglePageApplicationSample.cs", SinglePageApplicationSample.Create(), - Example.Page("Open the application", "/spa/"), - Example.Page("Open a client side route directly", "/spa/books/42", "The server delivers the application, which then renders the route.")), - - new("custom-framework", "Frameworks", "Custom Frameworks", "Builds your own framework on top of the reflection layer.", - Docs + "frameworks/custom/", "CustomFrameworkSample.cs", CustomFrameworkSample.Create(), - Example.Request("Call the exposed method", "GET", "/custom-framework/42"), - Example.Page("Browse the generated API", "/custom-framework/scalar/")), - - // Handlers - - new("layouting", "Handlers", "Layouting", "Allows an app to use multiple handlers by adding routing.", - Docs + "handlers/layouting/", "LayoutingSample.cs", LayoutingSample.Create(), - Example.Request("Call the API", "GET", "/layouting/api/"), - Example.Request("Fetch a file", "GET", "/layouting/assets/README.md")), - - new("static-files", "Handlers", "Static Files", "Serves static files from a directory.", - Docs + "handlers/files/", "StaticFileSample.cs", StaticFileSample.Create(), - Example.Request("Fetch a file", "GET", "/static-files/README.md")), - - new("api-docs", "Handlers", "API Documentation", "Generates an Open API definition and serves Swagger UI, Redoc and Scalar.", - Docs + "handlers/api-browsing/", "ApiDocumentationSample.cs", ApiDocumentationSample.Create(), - Example.Page("Swagger UI", "/api-docs/swagger/"), - Example.Page("Redoc", "/api-docs/redoc/"), - Example.Page("Scalar", "/api-docs/scalar/"), - Example.Request("Fetch the Open API definition", "GET", "/api-docs/openapi.json"), - Example.Request("Fetch a book that does not exist", "GET", "/api-docs/books/42", note: "404, as documented in the definition")), - - new("sse", "Handlers", "Server Sent Events", "A live dashboard that receives updates pushed by the server.", - Docs + "handlers/server-sent-events/", "ServerSentEventsSample.cs", ServerSentEventsSample.Create(), - Example.Page("Open the dashboard", "/sse/"), - Example.Shell("Watch the raw event stream", "curl -N {origin}/sse/stats/")), - - new("pages", "Handlers", "Pages", "Renders HTML pages from templates on the server.", - Docs + "handlers/pages/", "PagesSample.cs", PagesSample.Create(), - Example.Page("Page rendered from a template", "/pages/books/"), - Example.Page("Page in the server style", "/pages/about/")), - - new("virtual-hosting", "Handlers", "Virtual Hosting", "Hosts multiple websites, one per domain, on a single server.", - Docs + "handlers/virtual-hosts/", "VirtualHostingSample.cs", VirtualHostingSample.Create(), - Example.Page("Open the blog", "http://blog.localhost:8080/virtual-hosting/"), - Example.Page("Open the shop", "http://shop.localhost:8080/virtual-hosting/"), - Example.Page("Open with any other host", "/virtual-hosting/", "Redirects to the blog."), - Example.Shell("Choose the site via the Host header", "curl -H \"Host: shop.localhost\" {origin}/virtual-hosting/")), - - new("load-balancing", "Handlers", "Load Balancing", "Distributes requests over workers and mirrors, with a canary deployment.", - Docs + "handlers/load-balancer/", "LoadBalancerSample.cs", LoadBalancerSample.Create(), - Example.Request("Call a worker", "GET", "/load-balancing/api/", note: "502, unless workers run on ports 5001 and 5002"), - Example.Request("Call the canary worker", "GET", "/load-balancing/api/", headers: new() { ["X-Canary"] = "1" }, note: "502, unless a worker runs on port 5003"), - Example.Shell("Download from a mirror", "curl -i {origin}/load-balancing/downloads/setup.exe", "Redirects to one of the mirrors.")), - - // Concerns - - new("authentication", "Concerns", "Authentication", "Secures an API with API keys, roles and per-user data.", - Docs + "concerns/authentication/", "AuthenticationSample.cs", AuthenticationSample.Create(), - Example.Request("Add a note as Alice", "PUT", "/authentication/notes/", "Buy milk", new() { ["X-API-Key"] = "alice-key", ["Content-Type"] = "text/plain" }), - Example.Request("List the notes of Alice", "GET", "/authentication/notes/", headers: new() { ["X-API-Key"] = "alice-key" }), - Example.Request("List all notes as Alice", "GET", "/authentication/notes/all", headers: new() { ["X-API-Key"] = "alice-key" }, note: "403, Alice is no administrator"), - Example.Request("List all notes as Bob", "GET", "/authentication/notes/all", headers: new() { ["X-API-Key"] = "bob-key" }), - Example.Request("Call without a key", "GET", "/authentication/notes/", note: "401")), - - new("cors", "Concerns", "CORS", "Allows a frontend on another origin to call the API from the browser.", - Docs + "concerns/cors/", "CorsSample.cs", CorsSample.Create(), - Example.Request("List the todos", "GET", "/cors/api/todos/"), - Example.Shell("Send the preflight request of the frontend", - "curl -i -X OPTIONS -H \"Origin: http://localhost:5173\" -H \"Access-Control-Request-Method: PUT\" {origin}/cors/api/todos/", - "Browsers send this before the actual request. Try another origin to see the CORS headers disappear.")), - - new("errors", "Concerns", "Error Handling", "JSON errors for the API, HTML error pages for the website, custom mapping.", - Docs + "concerns/error-handling/", "ErrorHandlingSample.cs", ErrorHandlingSample.Create(), - Example.Request("Fetch an order", "GET", "/errors/api/orders/1"), - Example.Request("Fetch an order that does not exist", "GET", "/errors/api/orders/42", note: "404 as JSON"), - Example.Request("Order something that is sold out", "POST", "/errors/api/orders/", """{ "product": "Tea" }""", Json, "409, mapped from a custom exception"), - Example.Page("Open a page that does not exist", "/errors/does-not-exist", "404 as HTML page")), - - new("localization", "Concerns", "Localization", "Responds in the language preferred by the user.", - Docs + "concerns/localization/", "LocalizationSample.cs", LocalizationSample.Create(), - Example.Request("Prefer Swiss German", "GET", "/localization/greeting/", headers: new() { ["Accept-Language"] = "de-CH, en;q=0.8" }), - Example.Request("Choose French", "GET", "/localization/greeting/?lang=fr"), - Example.Request("Prefer Japanese", "GET", "/localization/greeting/", headers: new() { ["Accept-Language"] = "ja" }, note: "Not supported, falls back to English")), - - new("inspection", "Concerns", "Inspection", "Shows what the server received and responded, to debug clients.", - Docs + "concerns/inspection/", "InspectionSample.cs", InspectionSample.Create(), - Example.Request("Call the API", "GET", "/inspection/api/orders/?limit=5"), - Example.Request("Inspect the call", "GET", "/inspection/api/orders/?limit=5&inspect")), - - // Concepts - - new("dependency-injection", "Concepts", "Dependency Injection", "Lets the framework construct services and pass dependencies.", - Docs + "concepts/dependency-injection/", "DependencyInjectionSample.cs", DependencyInjectionSample.Create(), - Example.Request("List all books", "GET", "/dependency-injection/books/"), - Example.Request("Add a book", "PUT", "/dependency-injection/books/", """{ "title": "Dune" }""", Json)), - - // Use cases - - new("file-share", "Use Cases", "File Share", "Password protected directory listing with resumable downloads.", - Docs + "handlers/listing/", "FileShareSample.cs", FileShareSample.Create(), - Example.Page("Browse the files", "/file-share/", "Log in as \"friend\" with password \"secret\"."), - Example.Request("Download the first 100 bytes of a file", "GET", "/file-share/README.md", - headers: new() { ["Authorization"] = "Basic ZnJpZW5kOnNlY3JldA==", ["Range"] = "bytes=0-99" }, note: "206 Partial Content")), - - new("legacy-migration", "Use Cases", "Legacy Migration", "Replaces a legacy app step by step using a reverse proxy, redirects and new endpoints.", - Docs + "handlers/reverse-proxy/", "LegacyMigrationSample.cs", LegacyMigrationSample.Create(), - Example.Request("Call the rewritten API", "GET", "/legacy-migration/api/v2/status"), - Example.Request("Open a page that has moved", "GET", "/legacy-migration/contact.php", note: "301 to the rewritten page"), - Example.Request("Open a page of the legacy app", "GET", "/legacy-migration/login.php", note: "502, unless the legacy app runs on port 5000")) - ]; - -} diff --git a/Playground/Browser/Index.html b/Playground/Browser/Index.html deleted file mode 100644 index d7bc386c5..000000000 --- a/Playground/Browser/Index.html +++ /dev/null @@ -1,987 +0,0 @@ - - - - - - GenHTTP Playground - - - - - - -
    - - - - - diff --git a/Playground/Browser/Sample.cs b/Playground/Browser/Sample.cs deleted file mode 100644 index 4ca509e3b..000000000 --- a/Playground/Browser/Sample.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System.Text.Json.Serialization; - -using GenHTTP.Api.Content; - -namespace GenHTTP.Playground.Browser; - -/// The path the sample is served at, e.g. "webservices" for http://localhost:8080/webservices/ -/// The file name of the sample within the Samples folder -public sealed record Sample(string Segment, string Category, string Name, string Description, string Documentation, string Source, - [property: JsonIgnore] IHandlerBuilder Handler, params Example[] Examples); - -/// -/// A way to try a sample: a request sent from the sample browser, a page -/// opened in the browser or a shell command ("{origin}" is replaced by the -/// URL of the playground). -/// -public sealed record Example(string Kind, string Title, string? Method = null, string? Path = null, string? Body = null, - Dictionary? Headers = null, string? Command = null, string? Note = null) -{ - - public static Example Request(string title, string method, string path, string? body = null, Dictionary? headers = null, string? note = null) - => new("request", title, method, path, body, headers, Note: note); - - public static Example Page(string title, string path, string? note = null) - => new("page", title, Path: path, Note: note); - - public static Example Shell(string title, string command, string? note = null) - => new("shell", title, Command: command, Note: note); - -} diff --git a/Playground/Browser/SampleBrowser.cs b/Playground/Browser/SampleBrowser.cs deleted file mode 100644 index 7c6cf702f..000000000 --- a/Playground/Browser/SampleBrowser.cs +++ /dev/null @@ -1,43 +0,0 @@ -using GenHTTP.Api.Content; -using GenHTTP.Api.Protocol; - -using GenHTTP.Modules.Functional; -using GenHTTP.Modules.IO; -using GenHTTP.Modules.Layouting; - -namespace GenHTTP.Playground.Browser; - -/// -/// Serves all samples below their own path, together with a page -/// at the root that lists them and allows to call them. -/// -internal static class SampleBrowser -{ - private static readonly ContentType SourceType = new("text/plain; charset=utf-8"); - - internal static IHandlerBuilder Create() - { - var sources = Layout.Create(); - - foreach (var sample in Catalog.Samples) - { - sources.Add(sample.Source, Content.From(Resource.FromAssembly($"Source.{sample.Source}").Type(SourceType))); - } - - var playground = Layout.Create() - .Add("samples", Inline.Create().Get(() => Catalog.Samples)) - .Add("source", sources); - - var app = Layout.Create() - .Index(Content.From(Resource.FromAssembly("Browser.Index.html"))) - .Add("playground", playground); - - foreach (var sample in Catalog.Samples) - { - app.Add(sample.Segment, sample.Handler); - } - - return app; - } - -} diff --git a/Playground/GenHTTP.Playground.csproj b/Playground/GenHTTP.Playground.csproj index f0ceac292..8baea9af3 100644 --- a/Playground/GenHTTP.Playground.csproj +++ b/Playground/GenHTTP.Playground.csproj @@ -3,7 +3,7 @@ Exe - net11.0 + net11.0 true false @@ -40,7 +40,6 @@ - @@ -57,20 +56,4 @@ - - - - - - - - - - - - - - - - diff --git a/Playground/Program.cs b/Playground/Program.cs index 019eaa8e8..7ab508e1f 100644 --- a/Playground/Program.cs +++ b/Playground/Program.cs @@ -1,25 +1,12 @@ using GenHTTP.Engine.Internal; -using GenHTTP.Modules.DependencyInjection; +using GenHTTP.Modules.IO; using GenHTTP.Modules.Practices; -using GenHTTP.Playground.Browser; -using GenHTTP.Playground.Samples; - -/* - * - * Serves all samples, open http://localhost:8080/ to browse them and call them - * from your browser. To run a single sample, pass it to the host instead, e.g. - * - * .Handler(WebserviceSample.Create()) - * - * The samples for the ioxide engine create their own host, see Samples/Ioxide/README.md. - * - */ +var app = Content.From(Resource.FromString("Hello World!")); return await Host.Create() - .Handler(SampleBrowser.Create()) - .AddDependencyInjection(DependencyInjectionSample.Services()) + .Handler(app) .Development() .Defaults() .RunAsync(); diff --git a/Playground/README.md b/Playground/README.md index b300abde6..2f078433d 100644 --- a/Playground/README.md +++ b/Playground/README.md @@ -1,68 +1,19 @@ # GenHTTP Playground -The playground provides code samples for quick reference and allows developers to -quickly validate things. +The playground is a minimal app to quickly try things out while working on GenHTTP. +Change the handler in [Program.cs](./Program.cs) as needed and start the server: ```bash cd Playground dotnet run ``` -Then open http://localhost:8080/ to browse the samples, read their code and call them -from your browser (or copy the equivalent `curl` command). All samples run on this one -server, each below its own path, e.g. `/webservices/`. +The app is then served at http://localhost:8080/. -To add a sample, create a class in [Samples](./Samples) with a `Create()` method returning -the handler and register it with a few example requests in [Browser/Catalog.cs](./Browser/Catalog.cs). +## Samples -## Frameworks - -| Sample | Description | -|----------------------------------------------------------------------|----------------------------------------------------------------------------------| -| [Webservices](./Samples/WebserviceSample.cs) | Implements a REST webservice via a handler class. | -| [Functional](./Samples/FunctionalSample.cs) | Uses delegates to implement a web service (similar to ASP.NET Core Minimal API). | -| [Controllers](./Samples/ControllerSample.cs) | Uses controllers to implement a web service (similar to ASP.NET Core MVC). | -| [Websockets](./Samples/WebsocketSample.cs) | A chat room that pushes messages to all connected browsers. | -| [MCP Tools](./Samples/McpSample.cs) | Provides tools to AI agents such as Claude via the Model Context Protocol. | -| [Static Websites](./Samples/StaticWebsiteSample.cs) | Hosts a static website (with `index.html` support). | -| [Single Page Applications](./Samples/SinglePageApplicationSample.cs) | Hosts a SPA such as a React or Angular application. | -| [Custom Frameworks](./Samples/CustomFrameworkSample.cs) | Builds your own framework on top of the reflection layer. | - -## Handlers - -| Sample | Description | -|---------------------------------------------------------|-----------------------------------------------------------------------------| -| [Layouting](./Samples/LayoutingSample.cs) | Allows an app to use multiple handlers by adding routing. | -| [Static Files](./Samples/StaticFileSample.cs) | Serves static files from a directory. | -| [API Documentation](./Samples/ApiDocumentationSample.cs) | Generates an Open API definition and serves Swagger UI, Redoc and Scalar. | -| [Server Sent Events](./Samples/ServerSentEventsSample.cs) | A live dashboard that receives updates pushed by the server. | -| [Pages](./Samples/PagesSample.cs) | Renders HTML pages from templates on the server. | -| [Virtual Hosting](./Samples/VirtualHostingSample.cs) | Hosts multiple websites, one per domain, on a single server. | -| [Load Balancing](./Samples/LoadBalancerSample.cs) | Distributes requests over workers and mirrors, with a canary deployment. | - -## Concerns - -| Sample | Description | -|-------------------------------------------------------|-------------------------------------------------------------------------------| -| [Authentication](./Samples/AuthenticationSample.cs) | Secures an API with API keys, roles and per-user data. | -| [CORS](./Samples/CorsSample.cs) | Allows a frontend on another origin to call the API from the browser. | -| [Error Handling](./Samples/ErrorHandlingSample.cs) | JSON errors for the API, HTML error pages for the website, custom mapping. | -| [Localization](./Samples/LocalizationSample.cs) | Responds in the language preferred by the user. | -| [Inspection](./Samples/InspectionSample.cs) | Shows what the server received and responded, to debug clients. | - -## Concepts - -| Sample | Description | -|-----------------------------------------------------------------|-----------------------------------------------------------------| -| [Dependency Injection](./Samples/DependencyInjectionSample.cs) | Lets the framework construct services and pass dependencies. | - -## Use Cases - -These samples combine multiple modules the way an application typically would. - -| Sample | Description | -|--------------------------------------------------------|-----------------------------------------------------------------------------------------------| -| [File Share](./Samples/FileShareSample.cs) | Password protected directory listing with resumable downloads. | -| [Legacy Migration](./Samples/LegacyMigrationSample.cs) | Replaces a legacy app step by step using a reverse proxy, redirects and new endpoints. | +Samples for the frameworks, handlers and concerns of GenHTTP can be found in the +[playground on the website](https://genhttp.org/playground/), where you can read their +code and send requests to them as they run live. The [Ioxide](./Samples/Ioxide/README.md) folder contains samples for the io_uring based engine. diff --git a/Playground/Resources/Spa/app.js b/Playground/Resources/Spa/app.js deleted file mode 100644 index 317cfaa73..000000000 --- a/Playground/Resources/Spa/app.js +++ /dev/null @@ -1,24 +0,0 @@ -// a minimal client side router, as React Router or the Angular router would provide it -const base = document.baseURI; - -function render() { - const route = location.href.substring(base.length); - - document.getElementById('view').textContent = (route === '') - ? 'Home - reload the page on any route, the server will always deliver this application.' - : `Route "${route}" rendered in the browser.`; -} - -document.addEventListener('click', (event) => { - const link = event.target.closest('[data-route]'); - - if (link) { - event.preventDefault(); - history.pushState(null, '', link.href); - render(); - } -}); - -window.addEventListener('popstate', render); - -render(); diff --git a/Playground/Resources/Spa/index.html b/Playground/Resources/Spa/index.html deleted file mode 100644 index 65101fc8a..000000000 --- a/Playground/Resources/Spa/index.html +++ /dev/null @@ -1,17 +0,0 @@ - - - - - Single Page Application - - - - - -
    - - - diff --git a/Playground/Resources/Website/about/index.html b/Playground/Resources/Website/about/index.html deleted file mode 100644 index 7b67571c3..000000000 --- a/Playground/Resources/Website/about/index.html +++ /dev/null @@ -1,12 +0,0 @@ - - - - - About - - - -

    About

    -

    Served from about/index.html. Back

    - - diff --git a/Playground/Resources/Website/index.html b/Playground/Resources/Website/index.html deleted file mode 100644 index e0713c29a..000000000 --- a/Playground/Resources/Website/index.html +++ /dev/null @@ -1,13 +0,0 @@ - - - - - Static Website - - - -

    Static Website

    -

    This page is index.html, served for the root of the website.

    -

    About is a folder with its own index.html.

    - - diff --git a/Playground/Resources/Website/styles.css b/Playground/Resources/Website/styles.css deleted file mode 100644 index d4a62db20..000000000 --- a/Playground/Resources/Website/styles.css +++ /dev/null @@ -1,6 +0,0 @@ -body { - font-family: system-ui, sans-serif; - max-width: 40rem; - margin: 3rem auto; - line-height: 1.5; -} diff --git a/Playground/Samples/ApiDocumentationSample.cs b/Playground/Samples/ApiDocumentationSample.cs deleted file mode 100644 index 55e818a24..000000000 --- a/Playground/Samples/ApiDocumentationSample.cs +++ /dev/null @@ -1,75 +0,0 @@ -using GenHTTP.Api.Content; -using GenHTTP.Api.Protocol; - -using GenHTTP.Modules.ApiBrowsing; -using GenHTTP.Modules.Layouting; -using GenHTTP.Modules.OpenApi; -using GenHTTP.Modules.Reflection; -using GenHTTP.Modules.Webservices; - -namespace GenHTTP.Playground.Samples; - -public static class ApiDocumentationSample -{ - - public static IHandlerBuilder Create() - { - /* - * - * Generates an Open API definition for a web service and lets developers - * explore and try the API in their browser. The viewers are hosted by the - * server itself, so no internet connection is required. - * - * Works the same way for functional handlers and controllers. - * - * See https://genhttp.org/documentation/content/concerns/open-api/ - * and https://genhttp.org/documentation/content/handlers/api-browsing/ - * - */ - - return Layout.Create() - .AddService("books") - .AddOpenApi() // GET http://localhost:8080/api-docs/openapi.json (or .yaml) - .AddSwaggerUi() // GET http://localhost:8080/api-docs/swagger/ - .AddRedoc() // GET http://localhost:8080/api-docs/redoc/ - .AddScalar(title: "Book API"); // GET http://localhost:8080/api-docs/scalar/ - } - - public record Book(int Id, string Title); - - public class BookService - { - private static readonly List Books = - [ - new(1, "Lord of the Rings") - ]; - - [ResourceMethod] - public List List() => Books; - - [ResourceMethod(":id")] - public Book Get(int id) - => Books.FirstOrDefault(b => b.Id == id) ?? throw new ProviderException(ResponseStatus.NotFound, $"There is no book with id {id}"); - - [ResourceMethod(Method.Put)] - public Book Create(Book book) - { - var toAdd = book with - { - Id = Books.Select(b => b.Id).DefaultIfEmpty().Max() + 1 - }; - - Books.Add(toAdd); - - return toAdd; - } - - [ResourceMethod(Method.Delete, ":id")] - public void Delete(int id) - { - Books.RemoveAll(b => b.Id == id); - } - - } - -} diff --git a/Playground/Samples/AuthenticationSample.cs b/Playground/Samples/AuthenticationSample.cs deleted file mode 100644 index 06b4ad1e4..000000000 --- a/Playground/Samples/AuthenticationSample.cs +++ /dev/null @@ -1,92 +0,0 @@ -using GenHTTP.Api.Content; -using GenHTTP.Api.Content.Authentication; -using GenHTTP.Api.Protocol; - -using GenHTTP.Modules.Authentication; -using GenHTTP.Modules.Layouting; -using GenHTTP.Modules.Reflection; -using GenHTTP.Modules.Reflection.Injectors; -using GenHTTP.Modules.Webservices; - -namespace GenHTTP.Playground.Samples; - -public static class AuthenticationSample -{ - - public static IHandlerBuilder Create() - { - /* - * - * A notes API secured with API keys. Every user only sees their own notes, - * while administrators may see the notes of all users. - * - * Clients send their key via the "X-API-Key" header: "alice-key" for a user, - * "bob-key" for an administrator. - * - * Basic, bearer (JWT) and client certificate authentication work the same way. - * - * See https://genhttp.org/documentation/content/concerns/authentication/ - * - */ - - var auth = ApiKeyAuthentication.Create() - .Authenticator(AuthenticateAsync); - - // allows the service methods to declare the user as a parameter - var injection = Injection.Default() - .Add(new UserInjector()); - - return Layout.Create() - .AddService("notes", injectors: injection) - .Authentication(auth); - } - - private static ValueTask AuthenticateAsync(IRequest request, string key) - { - // this is where you would look up the key in your database - IUser? user = key switch - { - "alice-key" => new NoteUser("alice", "USER"), - "bob-key" => new NoteUser("bob", "USER", "ADMIN"), - _ => null // unknown key, access denied - }; - - return new(user); - } - - public record NoteUser(string Name, params string[] Roles) : IUser - { - - public string DisplayName => Name; - - } - - public record Note(string Owner, string Text); - - public class NoteService - { - private static readonly List Notes = []; - - // GET http://localhost:8080/authentication/notes/ - [ResourceMethod] - public List Mine(NoteUser user) => Notes.Where(n => n.Owner == user.Name).ToList(); - - // PUT http://localhost:8080/authentication/notes/ with the text as body - [ResourceMethod(Method.Put)] - public Note Add(NoteUser user, [FromBody] string text) - { - var note = new Note(user.Name, text); - - Notes.Add(note); - - return note; - } - - // GET http://localhost:8080/authentication/notes/all - [ResourceMethod("all")] - [RequireRole("ADMIN")] - public List All() => Notes; - - } - -} diff --git a/Playground/Samples/ControllerSample.cs b/Playground/Samples/ControllerSample.cs deleted file mode 100644 index 9a0a0ed12..000000000 --- a/Playground/Samples/ControllerSample.cs +++ /dev/null @@ -1,62 +0,0 @@ -using GenHTTP.Api.Content; - -using GenHTTP.Modules.Controllers; -using GenHTTP.Modules.Layouting; -using GenHTTP.Modules.Reflection; - -namespace GenHTTP.Playground.Samples; - -public static class ControllerSample -{ - - public static IHandlerBuilder Create() - { - /* - * - * Shows how to declare and register a controller that will be invoked - * to handle incoming HTTP requests. - * - * See https://genhttp.org/documentation/content/frameworks/controllers/ - * - */ - - return Layout.Create() - .AddController("books"); - } - - public record Book(int Id, string Title); - - public class BookController - { - private static readonly List Books = - [ - new(1, "Lord of the Rings") - ]; - - // GET http://localhost:8080/controllers/books/ - [ControllerAction(Method.Get)] - public List Index() => Books; - - // PUT http://localhost:8080/controllers/books/create/ with JSON/XML/... payload - [ControllerAction(Method.Put)] - public Book Create(Book book) - { - var toAdd = book with - { - Id = Books.Select(b => b.Id).DefaultIfEmpty().Max() + 1 - }; - - Books.Add(toAdd); - return toAdd; - } - - // DELETE http://localhost:8080/controllers/books/delete/1/ - [ControllerAction(Method.Delete)] - public void Delete([FromPath] int id) - { - Books.RemoveAll(b => b.Id == id); - } - - } - -} diff --git a/Playground/Samples/CorsSample.cs b/Playground/Samples/CorsSample.cs deleted file mode 100644 index d1e49668b..000000000 --- a/Playground/Samples/CorsSample.cs +++ /dev/null @@ -1,39 +0,0 @@ -using GenHTTP.Api.Content; -using GenHTTP.Api.Protocol; - -using GenHTTP.Modules.Functional; -using GenHTTP.Modules.Layouting; -using GenHTTP.Modules.Security; - -namespace GenHTTP.Playground.Samples; - -public static class CorsSample -{ - - public static IHandlerBuilder Create() - { - /* - * - * Allows a frontend hosted on another origin (e.g. a React app served by - * the Vite dev server on http://localhost:5173) to call this API from the browser. - * Browsers will block requests from any other origin. - * - * See https://genhttp.org/documentation/content/concerns/cors/ - * - */ - - var todos = new List { "Write the frontend" }; - - var api = Inline.Create() - .Get(() => todos) // GET http://localhost:8080/cors/api/todos/ - .Put((string todo) => todos.Add(todo)); // PUT http://localhost:8080/cors/api/todos/?todo=... - - var policy = CorsPolicy.Restrictive() - .Add("http://localhost:5173", [RequestMethod.Get, RequestMethod.Put], allowedHeaders: null, exposedHeaders: null, allowCredentials: false); - - return Layout.Create() - .Add("api/todos", api) - .Add(policy); - } - -} diff --git a/Playground/Samples/CustomFrameworkSample.cs b/Playground/Samples/CustomFrameworkSample.cs deleted file mode 100644 index 9da5b6b86..000000000 --- a/Playground/Samples/CustomFrameworkSample.cs +++ /dev/null @@ -1,81 +0,0 @@ -using GenHTTP.Api.Content; -using GenHTTP.Api.Infrastructure; -using GenHTTP.Api.Protocol; - -using GenHTTP.Modules.ApiBrowsing; -using GenHTTP.Modules.Conversion; -using GenHTTP.Modules.Functional.Provider; -using GenHTTP.Modules.Layouting; -using GenHTTP.Modules.OpenApi; -using GenHTTP.Modules.Reflection; -using GenHTTP.Modules.Reflection.Operations; - -namespace GenHTTP.Playground.Samples; - -public static class CustomFrameworkSample -{ - - public static IHandlerBuilder Create() - { - /* - * - * Shows how to implement a custom framework. - * - * See https://genhttp.org/documentation/content/frameworks/custom/ - * - */ - - return Layout.Create() - .Add(new CustomFrameworkHandler()) // GET http://localhost:8080/custom-framework/42 - .AddOpenApi() - .AddScalar(); // GET http://localhost:8080/custom-framework/scalar/ - } - - public class CustomFrameworkHandler : IHandler, IServiceMethodProvider - { - private MethodCollection? _methods; - - public MethodCollection Methods => _methods ?? throw new InvalidOperationException("Handler is not prepared yet"); - - public async ValueTask PrepareAsync(IServer server) - { - var list = new List(); - - // specify the supported methods of the operation we are exposing - var supportedMethods = new MethodConfiguration([RequestMethod.Get]); - - // the actual piece of code to be executed - either a method info or a delegate - var methodInfo = GetType().GetMethod("ExposedMethod")!; - - // auto enables code generation, otherwise reflection only - var executionSettings = new ExecutionSettings(ExecutionMode.Auto); - - // configures the behavior for serialization, injection and formatting - var registry = new MethodRegistry( - Serialization.Default().Build(), - Injection.Default().Build(), - Formatting.Default().Build() - ); - - // build the operation we would like to provide - var operation = OperationBuilder.Create(server, ":id", methodInfo, null, executionSettings, supportedMethods, registry); - - // create a method handler from the operation which will serve it as an HTTP endpoint - // this handler requires an instance provider which tells the framework on which - // object to invoke the given method info or delegate - list.Add(new MethodHandler(operation, (_) => new(this), registry)); - - // build a method collection handler from all collected operations - // this handler is responsible for routing - _methods = new MethodCollection(list); - - await _methods.PrepareAsync(server); - } - - public ValueTask HandleAsync(IRequest request) => Methods.HandleAsync(request); - - public string ExposedMethod(int id) => id.ToString(); - - } - -} diff --git a/Playground/Samples/DependencyInjectionSample.cs b/Playground/Samples/DependencyInjectionSample.cs deleted file mode 100644 index 659573228..000000000 --- a/Playground/Samples/DependencyInjectionSample.cs +++ /dev/null @@ -1,99 +0,0 @@ -using GenHTTP.Api.Content; - -using GenHTTP.Modules.DependencyInjection; -using GenHTTP.Modules.Layouting; -using GenHTTP.Modules.Reflection; -using GenHTTP.Modules.Webservices; - -using Microsoft.Extensions.DependencyInjection; - -namespace GenHTTP.Playground.Samples; - -public static class DependencyInjectionSample -{ - - public static IHandlerBuilder Create() - { - /* - * - * Lets the framework create services and pass their dependencies, so the - * services do not need to know how to construct them (and can be tested - * with fakes). - * - * Dependency injection needs to be enabled on the host, see Services() below - * and Program.cs: - * - * Host.Create() - * .AddDependencyInjection(DependencyInjectionSample.Services()) - * - * See https://genhttp.org/documentation/content/concepts/dependency-injection/ - * - */ - - return Layout.Create() - .AddDependentService("books"); // GET http://localhost:8080/dependency-injection/books/ - } - - public static IServiceProvider Services() - { - var services = new ServiceCollection(); - - services.AddSingleton() - .AddSingleton(TimeProvider.System); - - return services.BuildServiceProvider(); - } - - public record Book(int Id, string Title, DateTimeOffset? Added = null); - - public interface IBookRepository - { - - List GetAll(); - - Book Add(Book book); - - } - - public class InMemoryBookRepository : IBookRepository - { - private readonly List _books = [new(1, "Lord of the Rings")]; - - private readonly Lock _sync = new(); - - public List GetAll() - { - lock (_sync) - { - return [.._books]; - } - } - - public Book Add(Book book) - { - lock (_sync) - { - var toAdd = book with { Id = _books.Select(b => b.Id).DefaultIfEmpty().Max() + 1 }; - - _books.Add(toAdd); - - return toAdd; - } - } - - } - - // dependencies can be injected via the constructor ... - public class BookService(IBookRepository repository) - { - - [ResourceMethod] - public List List() => repository.GetAll(); - - // ... or as a method parameter - [ResourceMethod(Method.Put)] - public Book Add(Book book, TimeProvider time) => repository.Add(book with { Added = time.GetUtcNow() }); - - } - -} diff --git a/Playground/Samples/ErrorHandlingSample.cs b/Playground/Samples/ErrorHandlingSample.cs deleted file mode 100644 index 5e92fc171..000000000 --- a/Playground/Samples/ErrorHandlingSample.cs +++ /dev/null @@ -1,77 +0,0 @@ -using GenHTTP.Api.Content; -using GenHTTP.Api.Protocol; - -using GenHTTP.Modules.ErrorHandling; -using GenHTTP.Modules.Functional; -using GenHTTP.Modules.IO; -using GenHTTP.Modules.Layouting; - -namespace GenHTTP.Playground.Samples; - -public static class ErrorHandlingSample -{ - - public static IHandlerBuilder Create() - { - /* - * - * A shop with a website for humans and an API for machines. Errors in the API - * are reported as JSON (or XML, ... as requested by the client), while the website - * renders HTML error pages. Exceptions thrown by the business logic are mapped - * to HTTP status codes without the business logic knowing about HTTP. - * - * See https://genhttp.org/documentation/content/concerns/error-handling/ - * - */ - - var orders = Inline.Create() - // GET http://localhost:8080/errors/api/orders/42 (404 as JSON) - .Get(":id", (int id) => (id == 1) ? new Order(1, "Coffee") : throw new ProviderException(ResponseStatus.NotFound, $"There is no order with id {id}")) - // POST http://localhost:8080/errors/api/orders/ (409 via the custom mapper) - .Post((Order order) => Shop.PlaceOrder(order)) - .Add(ErrorHandler.From(new OutOfStockMapper())); - - var website = Layout.Create() - .Index(Content.From(Resource.FromString("

    Welcome to our shop!

    ").Type(ContentType.TextHtml))) - .Add(ErrorHandler.Html()); - - return Layout.Create() - .Add("api/orders", orders) - .Add(website); // e.g. GET http://localhost:8080/errors/does-not-exist (404 as HTML page) - } - - public record Order(int Id, string Product); - - public class OutOfStockException(string product) : Exception($"Sorry, '{product}' is sold out") - { - - public string Product => product; - - } - - public static class Shop - { - - public static Order PlaceOrder(Order order) => throw new OutOfStockException(order.Product); - - } - - public class OutOfStockMapper : IErrorMapper - { - - public ValueTask Map(IRequest request, IHandler handler, OutOfStockException error, ByteString? acceptedFormat) - { - var response = request.Respond() - .Status(ResponseStatus.Conflict) - .Content(error.Message, ContentType.TextPlain) - .Build(); - - return new(response); - } - - // null passes the request on, so the default error handling renders the 404 - public ValueTask GetNotFound(IRequest request, IHandler handler, ByteString? acceptedFormat) => new(); - - } - -} diff --git a/Playground/Samples/FileShareSample.cs b/Playground/Samples/FileShareSample.cs deleted file mode 100644 index 202446a06..000000000 --- a/Playground/Samples/FileShareSample.cs +++ /dev/null @@ -1,37 +0,0 @@ -using GenHTTP.Api.Content; - -using GenHTTP.Modules.Authentication; -using GenHTTP.Modules.DirectoryBrowsing; -using GenHTTP.Modules.IO; - -namespace GenHTTP.Playground.Samples; - -public static class FileShareSample -{ - - public static IHandlerBuilder Create() - { - /* - * - * Shares a folder with friends: they log in with their browser, browse - * through the files and download them. Downloads of large files can be - * paused and resumed, as range requests are supported. - * - * Open http://localhost:8080/file-share/ and log in as "friend" / "secret". - * - * See https://genhttp.org/documentation/content/handlers/listing/ - * and https://genhttp.org/documentation/content/concerns/range-support/ - * - */ - - var files = ResourceTree.FromDirectory("./"); - - var auth = BasicAuthentication.Create() - .Add("friend", "secret"); - - return Listing.From(files) - .AddRangeSupport() - .Authentication(auth); - } - -} diff --git a/Playground/Samples/FunctionalSample.cs b/Playground/Samples/FunctionalSample.cs deleted file mode 100644 index 636d14dc4..000000000 --- a/Playground/Samples/FunctionalSample.cs +++ /dev/null @@ -1,47 +0,0 @@ -using GenHTTP.Api.Content; - -using GenHTTP.Modules.Functional; -using GenHTTP.Modules.Layouting; - -namespace GenHTTP.Playground.Samples; - -public static class FunctionalSample -{ - - public static IHandlerBuilder Create() - { - /* - * - * Shows how to use delegates that will be invoked - * to handle incoming HTTP requests. - * - * See https://genhttp.org/documentation/content/frameworks/functional/ - * - */ - - var books = new List() - { - new(1, "Lord of the Rings") - }; - - var service = Inline.Create() - .Get(() => books) // GET http://localhost:8080/functional/books/ - .Put((Book book) => // PUT http://localhost:8080/functional/books/ with JSON/XML/... payload - { - var toAdd = book with - { - Id = books.Select(b => b.Id).DefaultIfEmpty().Max() + 1 - }; - - books.Add(toAdd); - return toAdd; - }) - .Delete(":id", (int id) => books.RemoveAll(b => b.Id == id)); // DELETE http://localhost:8080/functional/books/1 - - return Layout.Create() - .Add("books", service); - } - - public record Book(int Id, string Title); - -} diff --git a/Playground/Samples/InspectionSample.cs b/Playground/Samples/InspectionSample.cs deleted file mode 100644 index bbc91e7df..000000000 --- a/Playground/Samples/InspectionSample.cs +++ /dev/null @@ -1,36 +0,0 @@ -using GenHTTP.Api.Content; - -using GenHTTP.Modules.Functional; -using GenHTTP.Modules.Inspection; -using GenHTTP.Modules.Layouting; - -namespace GenHTTP.Playground.Samples; - -public static class InspectionSample -{ - - public static IHandlerBuilder Create() - { - /* - * - * Helps to find out why a client receives a certain response. Append "?inspect" - * to any URL to see the request as the server received it, together with - * the response the server would have sent. - * - * As this exposes details about your server, only add it while developing. - * - * See https://genhttp.org/documentation/content/concerns/inspection/ - * - */ - - var orders = Inline.Create() - .Get((int limit) => Enumerable.Range(1, limit).Select(i => new Order(i))); - - return Layout.Create() - .Add("api/orders", orders) // GET http://localhost:8080/inspection/api/orders/?limit=5&inspect - .AddInspector(); - } - - public record Order(int Id); - -} diff --git a/Playground/Samples/LayoutingSample.cs b/Playground/Samples/LayoutingSample.cs deleted file mode 100644 index cf5b7b54e..000000000 --- a/Playground/Samples/LayoutingSample.cs +++ /dev/null @@ -1,38 +0,0 @@ -using GenHTTP.Api.Content; - -using GenHTTP.Modules.Files; -using GenHTTP.Modules.Functional; -using GenHTTP.Modules.Layouting; - -namespace GenHTTP.Playground.Samples; - -public static class LayoutingSample -{ - - public static IHandlerBuilder Create() - { - /* - * - * Layouts allow you to structure your web application and divide it into - * different logical parts. The layout will route incoming requests to the designated - * handler. Layouts can be nested as needed. - * - * See https://genhttp.org/documentation/content/handlers/layouting/ - * - */ - - // serve static files from the current directory - var assets = Assets.From("./"); - - // define a simple REST API - var api = Inline.Create() - .Get(() => "Hello World!"); - - // assemble our application from the parts above and - // register them at the given URLs - return Layout.Create() - .Add("assets", assets) // e.g. GET http://localhost:8080/layouting/assets/README.md - .Add("api", api); // e.g. GET http://localhost:8080/layouting/api/ - } - -} diff --git a/Playground/Samples/LegacyMigrationSample.cs b/Playground/Samples/LegacyMigrationSample.cs deleted file mode 100644 index 96456e4cf..000000000 --- a/Playground/Samples/LegacyMigrationSample.cs +++ /dev/null @@ -1,49 +0,0 @@ -using GenHTTP.Api.Content; -using GenHTTP.Api.Protocol; - -using GenHTTP.Modules.Functional; -using GenHTTP.Modules.IO; -using GenHTTP.Modules.Layouting; -using GenHTTP.Modules.Redirects; -using GenHTTP.Modules.ReverseProxy; - -namespace GenHTTP.Playground.Samples; - -public static class LegacyMigrationSample -{ - - public static IHandlerBuilder Create() - { - /* - * - * Replaces a legacy web application step by step: GenHTTP sits in front of - * the old application and serves the parts that have already been rewritten. - * Moved pages are redirected, everything else is still served by the legacy - * application (expected to run on http://localhost:5000). - * - * See https://genhttp.org/documentation/content/handlers/reverse-proxy/ - * and https://genhttp.org/documentation/content/handlers/redirects/ - * - */ - - var newApi = Inline.Create() - .Get("status", () => new Status(true)); - - var contact = Content.From(Resource.FromString("

    Contact us

    ").Type(ContentType.TextHtml)); - - var legacy = Proxy.Create() - .Upstream("http://localhost:5000/") - .ConnectTimeout(TimeSpan.FromSeconds(5)) - .ReadTimeout(TimeSpan.FromSeconds(30)); - - return Layout.Create() - .Add("api/v2", newApi) // GET http://localhost:8080/legacy-migration/api/v2/status - .Add("contact", contact) - .Add("contact.php", Redirect.To("/legacy-migration/contact")) // permanent, so search engines learn the new URL - .Add("shop", Redirect.To("https://shop.example.com/", temporary: true)) - .Add(legacy); // everything else, e.g. GET http://localhost:8080/legacy-migration/login.php - } - - public record Status(bool Healthy); - -} diff --git a/Playground/Samples/LoadBalancerSample.cs b/Playground/Samples/LoadBalancerSample.cs deleted file mode 100644 index e6fe6f821..000000000 --- a/Playground/Samples/LoadBalancerSample.cs +++ /dev/null @@ -1,44 +0,0 @@ -using GenHTTP.Api.Content; -using GenHTTP.Api.Infrastructure; -using GenHTTP.Api.Protocol; - -using GenHTTP.Modules.Layouting; -using GenHTTP.Modules.LoadBalancing; - -namespace GenHTTP.Playground.Samples; - -public static class LoadBalancerSample -{ - - private static readonly ByteString CanaryHeader = new("X-Canary"); - - public static IHandlerBuilder Create() - { - /* - * - * Distributes API requests over multiple worker processes (expected to run - * on http://localhost:5001 and :5002) and sends clients downloading files - * to one of the mirror servers. - * - * Clients sending an "X-Canary" header are served by a canary worker - * (on http://localhost:5003), so a new version can be tested with real traffic. - * - * See https://genhttp.org/documentation/content/handlers/load-balancer/ - * - */ - - var workers = LoadBalancer.Create() - .Proxy("http://localhost:5001/") - .Proxy("http://localhost:5002/") - .Proxy("http://localhost:5003/", r => r.Header.Headers.ContainsKey(CanaryHeader) ? Priority.High : Priority.Low); - - var mirrors = LoadBalancer.Create() - .Redirect("https://mirror1.example.com/") - .Redirect("https://mirror2.example.com/"); - - return Layout.Create() - .Add("api", workers) // GET http://localhost:8080/load-balancing/api/ - .Add("downloads", mirrors); // GET http://localhost:8080/load-balancing/downloads/setup.exe - } - -} diff --git a/Playground/Samples/LocalizationSample.cs b/Playground/Samples/LocalizationSample.cs deleted file mode 100644 index 1cc99be76..000000000 --- a/Playground/Samples/LocalizationSample.cs +++ /dev/null @@ -1,53 +0,0 @@ -using System.Globalization; - -using GenHTTP.Api.Content; - -using GenHTTP.Modules.Functional; -using GenHTTP.Modules.I18n; -using GenHTTP.Modules.Layouting; - -namespace GenHTTP.Playground.Samples; - -public static class LocalizationSample -{ - - public static IHandlerBuilder Create() - { - /* - * - * Greets users in their preferred language and formats dates the way - * they are used to. The language is taken from the "lang" query parameter - * or the Accept-Language header sent by the browser. - * - * See https://genhttp.org/documentation/content/concerns/localization/ - * - */ - - var greetings = new Dictionary - { - ["en"] = "Hello", - ["de"] = "Hallo", - ["fr"] = "Bonjour" - }; - - var greeting = Inline.Create() - .Get(() => - { - var culture = CultureInfo.CurrentCulture; - - return $"{greetings[culture.TwoLetterISOLanguageName]}! {DateTime.Now.ToString("D", culture)}"; - }); - - var localization = Localization.Create() - .FromQuery("lang") - .FromHeader() - .Supports(culture => greetings.ContainsKey(culture.TwoLetterISOLanguageName)) // accepts regional variants such as de-CH - .Default(CultureInfo.GetCultureInfo("en")) - .Setter(currentCulture: true, currentUiCulture: true); - - return Layout.Create() - .Add("greeting", greeting) // GET http://localhost:8080/localization/greeting/?lang=fr - .Add(localization); - } - -} diff --git a/Playground/Samples/McpSample.cs b/Playground/Samples/McpSample.cs deleted file mode 100644 index fabb8a4fa..000000000 --- a/Playground/Samples/McpSample.cs +++ /dev/null @@ -1,74 +0,0 @@ -using System.ComponentModel.DataAnnotations; - -using GenHTTP.Api.Content; -using GenHTTP.Api.Content.Documentation; -using GenHTTP.Api.Protocol; - -using GenHTTP.Modules.Mcp; - -namespace GenHTTP.Playground.Samples; - -public static class McpSample -{ - - public static IHandlerBuilder Create() - { - /* - * - * Shows how to provide tools to AI agents such as Claude via the - * Model Context Protocol (MCP). - * - * Add the endpoint to Claude Code via - * - * claude mcp add --transport http library http://localhost:8080/mcp - * - * and ask, for example, "Which books about Rome are in the library?". - * - * See https://genhttp.org/documentation/content/frameworks/mcp/ - * - */ - - return Tools.Create() - .Server("library", "1.0.0", "Library") - .Instructions("Search for books before lending them to a reader.") - .Add() - .Add("get_time", "Returns the current time of the library (UTC)", [Tool(ReadOnly = true)] () => DateTime.UtcNow); - } - - public record Book(int Id, string Title, string? LentTo); - - public class LibraryTools - { - private static readonly List Books = - [ - new(1, "SPQR: A History of Ancient Rome", null), - new(2, "The Lord of the Rings", null) - ]; - - [Tool(ReadOnly = true)] - [Summary("Searches the books of the library by title")] - public List FindBooks([Summary("Part of the title, e.g. 'Rome'")] string query, [Range(1, 50)] int limit = 10) - => Books.Where(b => b.Title.Contains(query, StringComparison.OrdinalIgnoreCase)).Take(limit).ToList(); - - [Tool(Destructive = false)] - [Summary("Lends a book to a reader")] - public Book LendBook([Summary("The id of the book, as returned by find_books")] int bookId, [Summary("The name of the reader")] string reader) - { - var book = Books.FirstOrDefault(b => b.Id == bookId) - ?? throw new ProviderException(ResponseStatus.NotFound, $"There is no book with id {bookId}."); - - if (book.LentTo != null) - { - throw new ProviderException(ResponseStatus.Conflict, $"'{book.Title}' is already lent to {book.LentTo}."); - } - - var lent = book with { LentTo = reader }; - - Books[Books.IndexOf(book)] = lent; - - return lent; - } - - } - -} diff --git a/Playground/Samples/PagesSample.cs b/Playground/Samples/PagesSample.cs deleted file mode 100644 index 43931358c..000000000 --- a/Playground/Samples/PagesSample.cs +++ /dev/null @@ -1,82 +0,0 @@ -using Cottle; - -using GenHTTP.Api.Content; -using GenHTTP.Api.Protocol; - -using GenHTTP.Modules.Functional; -using GenHTTP.Modules.IO; -using GenHTTP.Modules.Layouting; -using GenHTTP.Modules.Pages; - -namespace GenHTTP.Playground.Samples; - -public static class PagesSample -{ - - public static IHandlerBuilder Create() - { - /* - * - * Renders simple HTML pages on the server, e.g. for an internal admin - * tool that does not justify a frontend framework. - * - * Templates are usually embedded into the assembly and loaded via - * Resource.FromAssembly("Books.html"). - * - * See https://genhttp.org/documentation/content/handlers/pages/ - * - */ - - var template = Renderer.From(Resource.FromString(BooksTemplate).Build()); - - var books = Inline.Create() - .Get(async (IRequest request) => - { - var model = new Dictionary - { - ["books"] = Value.FromEnumerable(Books.Select(b => Value.FromDictionary(new Dictionary - { - ["id"] = b.Id, - ["title"] = b.Title.Escaped() // the template engine does not escape HTML for you - }))) - }; - - return request.GetPage(await template.RenderAsync(model)); - }); - - var about = Inline.Create() - .Get(async (IRequest request) => request.GetPage(await Renderer.Server.RenderAsync("About", "

    This library runs on GenHTTP.

    "))); - - return Layout.Create() - .Add("books", books) // GET http://localhost:8080/pages/books/ (rendered from a Cottle template) - .Add("about", about); // GET http://localhost:8080/pages/about/ (in the style of the server's own pages) - } - - public record Book(int Id, string Title); - - private static readonly List Books = - [ - new(1, "Lord of the Rings"), - new(2, "Pride & Prejudice") - ]; - - private const string BooksTemplate = - """ - - - - - Books - - - - - {for book in books: - - } -
    IDTitle
    {book.id}{book.title}
    - - - """; - -} diff --git a/Playground/Samples/ServerSentEventsSample.cs b/Playground/Samples/ServerSentEventsSample.cs deleted file mode 100644 index 97a11beb0..000000000 --- a/Playground/Samples/ServerSentEventsSample.cs +++ /dev/null @@ -1,88 +0,0 @@ -using System.Diagnostics; - -using GenHTTP.Api.Content; -using GenHTTP.Api.Protocol; - -using GenHTTP.Modules.IO; -using GenHTTP.Modules.Layouting; -using GenHTTP.Modules.ServerSentEvents; - -namespace GenHTTP.Playground.Samples; - -public static class ServerSentEventsSample -{ - - public static IHandlerBuilder Create() - { - /* - * - * A live dashboard: the server pushes its current memory usage to - * the browser every second, without the client polling for it. - * - * See https://genhttp.org/documentation/content/handlers/server-sent-events/ - * - */ - - var stats = EventSource.Create() - .Generator(SendStatsAsync); - - var client = Content.From(Resource.FromString(ClientPage).Type(ContentType.TextHtml)); - - return Layout.Create() - .Index(client) // GET http://localhost:8080/sse/ - .Add("stats", stats); // GET http://localhost:8080/sse/stats/ - } - - public record ServerStats(long WorkingSet, long ManagedMemory, int Collections); - - private static async ValueTask SendStatsAsync(IEventConnection connection) - { - var id = 0; - - while (connection.Connected) - { - using var process = Process.GetCurrentProcess(); - - var stats = new ServerStats(process.WorkingSet64, GC.GetTotalMemory(false), GC.CollectionCount(0)); - - // serialized to JSON, the browser listens for the "stats" event type - await connection.DataAsync(stats, eventType: "stats", eventId: $"{id++}"); - - await Task.Delay(1000); - } - } - - private const string ClientPage = - """ - - - - - Server Stats - - -

    Server Stats

    -
    -
    Working set
    -
    -
    Managed memory
    -
    -
    Gen 0 collections
    -
    -
    - - - - """; - -} diff --git a/Playground/Samples/SinglePageApplicationSample.cs b/Playground/Samples/SinglePageApplicationSample.cs deleted file mode 100644 index a3aeb0775..000000000 --- a/Playground/Samples/SinglePageApplicationSample.cs +++ /dev/null @@ -1,30 +0,0 @@ -using GenHTTP.Api.Content; - -using GenHTTP.Modules.IO; -using GenHTTP.Modules.SinglePageApplications; - -namespace GenHTTP.Playground.Samples; - -public static class SinglePageApplicationSample -{ - - public static IHandlerBuilder Create() - { - /* - * - * Serves a single page application (SPA) from a directory (or resource tree in general). - * - * See https://genhttp.org/documentation/content/frameworks/single-page-applications/ - * - */ - - // embedded into the assembly here, use ResourceTree.FromDirectory("/var/app") to serve your build output - var files = ResourceTree.FromAssembly("Resources.Spa"); - - // GET http://localhost:8080/spa/books/42 serves index.html, the route is rendered in the browser - return SinglePageApplication.From(files) - .ServerSideRouting(); - } - -} - diff --git a/Playground/Samples/StaticFileSample.cs b/Playground/Samples/StaticFileSample.cs deleted file mode 100644 index acc2e5f15..000000000 --- a/Playground/Samples/StaticFileSample.cs +++ /dev/null @@ -1,24 +0,0 @@ -using GenHTTP.Api.Content; - -using GenHTTP.Modules.Files; - -namespace GenHTTP.Playground.Samples; - -public static class StaticFileSample -{ - - public static IHandlerBuilder Create() - { - /* - * - * Serves files from a given directory or resource tree. - * - * See https://genhttp.org/documentation/content/handlers/files/ - * - */ - - // e.g. GET http://localhost:8080/static-files/README.md - return Assets.From("./"); - } - -} diff --git a/Playground/Samples/StaticWebsiteSample.cs b/Playground/Samples/StaticWebsiteSample.cs deleted file mode 100644 index da3dd4723..000000000 --- a/Playground/Samples/StaticWebsiteSample.cs +++ /dev/null @@ -1,29 +0,0 @@ -using GenHTTP.Api.Content; - -using GenHTTP.Modules.IO; -using GenHTTP.Modules.StaticWebsites; - -namespace GenHTTP.Playground.Samples; - -public static class StaticWebsiteSample -{ - - public static IHandlerBuilder Create() - { - /* - * - * Serves a static website from a directory (or resource tree in general). - * - * See https://genhttp.org/documentation/content/frameworks/static-websites/ - * - */ - - // embedded into the assembly here, use ResourceTree.FromDirectory("/var/www") to serve a folder - var files = ResourceTree.FromAssembly("Resources.Website"); - - // GET http://localhost:8080/static-website/ serves index.html - return StaticWebsite.From(files); - } - -} - diff --git a/Playground/Samples/VirtualHostingSample.cs b/Playground/Samples/VirtualHostingSample.cs deleted file mode 100644 index c9065c793..000000000 --- a/Playground/Samples/VirtualHostingSample.cs +++ /dev/null @@ -1,38 +0,0 @@ -using GenHTTP.Api.Content; -using GenHTTP.Api.Protocol; - -using GenHTTP.Modules.IO; -using GenHTTP.Modules.Redirects; -using GenHTTP.Modules.VirtualHosting; - -namespace GenHTTP.Playground.Samples; - -public static class VirtualHostingSample -{ - - public static IHandlerBuilder Create() - { - /* - * - * Hosts multiple websites on a single server, one per domain. Browsers - * resolve *.localhost to your machine, so you can try this locally: - * - * http://blog.localhost:8080/virtual-hosting/ - * http://shop.localhost:8080/virtual-hosting/ - * http://localhost:8080/virtual-hosting/ (redirects to the blog) - * - * See https://genhttp.org/documentation/content/handlers/virtual-hosts/ - * - */ - - var blog = Content.From(Resource.FromString("

    My Blog

    ").Type(ContentType.TextHtml)); - - var shop = Content.From(Resource.FromString("

    My Shop

    ").Type(ContentType.TextHtml)); - - return VirtualHosts.Create() - .Add("blog.localhost", blog) - .Add("shop.localhost", shop) - .Default(Redirect.To("http://blog.localhost:8080/virtual-hosting/", temporary: true)); // any other host - } - -} diff --git a/Playground/Samples/WebserviceSample.cs b/Playground/Samples/WebserviceSample.cs deleted file mode 100644 index 338f6279a..000000000 --- a/Playground/Samples/WebserviceSample.cs +++ /dev/null @@ -1,64 +0,0 @@ -using GenHTTP.Api.Content; - -using GenHTTP.Modules.Controllers; -using GenHTTP.Modules.Layouting; -using GenHTTP.Modules.Reflection; -using GenHTTP.Modules.Webservices; - -namespace GenHTTP.Playground.Samples; - -public static class WebserviceSample -{ - - public static IHandlerBuilder Create() - { - /* - * - * Shows how to declare and register a class that will be invoked - * to handle incoming HTTP requests. - * - * See https://genhttp.org/documentation/content/frameworks/webservices/ - * - */ - - return Layout.Create() - .AddService("books"); - } - - public record Book(int Id, string Title); - - public class BookService - { - private static readonly List Books = - [ - new(1, "Lord of the Rings") - ]; - - // GET http://localhost:8080/webservices/books/ - [ResourceMethod] - public List List() => Books; - - // PUT http://localhost:8080/webservices/books/ with JSON/XML/... payload - [ResourceMethod(Method.Put)] - public Book Create(Book book) - { - var toAdd = book with - { - Id = Books.Select(b => b.Id).DefaultIfEmpty().Max() + 1 - }; - - Books.Add(toAdd); - - return toAdd; - } - - // DELETE http://localhost:8080/webservices/books/1 - [ResourceMethod(Method.Delete, ":id")] - public void Delete([FromPath] int id) - { - Books.RemoveAll(b => b.Id == id); - } - - } - -} diff --git a/Playground/Samples/WebsocketSample.cs b/Playground/Samples/WebsocketSample.cs deleted file mode 100644 index 12c38e2c9..000000000 --- a/Playground/Samples/WebsocketSample.cs +++ /dev/null @@ -1,143 +0,0 @@ -using GenHTTP.Api.Content; -using GenHTTP.Api.Protocol; - -using GenHTTP.Modules.IO; -using GenHTTP.Modules.Layouting; - -namespace GenHTTP.Playground.Samples; - -// imported here as the Websocket.Client package (referenced by the test project) declares a root namespace named "Websocket" -using GenHTTP.Modules.Websockets; - -public static class WebsocketSample -{ - - public static IHandlerBuilder Create() - { - /* - * - * A chat room: every message a client sends over the websocket is - * pushed to all connected clients. - * - * Open http://localhost:8080/websockets/ in two browser windows and start chatting. - * - * See https://genhttp.org/documentation/content/frameworks/websockets/ - * - */ - - var chat = Websocket.Reactive() - .Handler(new ChatHandler()); - - var client = Content.From(Resource.FromString(ClientPage).Type(ContentType.TextHtml)); - - return Layout.Create() - .Index(client) // GET http://localhost:8080/websockets/ - .Add("chat", chat); // ws://localhost:8080/websockets/chat - } - - public record ChatMessage(string Author, string Text, DateTime? Sent = null); - - public class ChatHandler : IReactiveHandler - { - private readonly List _clients = []; - - // connections are not thread-safe, so we never write to them concurrently - private readonly SemaphoreSlim _sync = new(1, 1); - - public async ValueTask OnConnected(IReactiveConnection connection) - { - await _sync.WaitAsync(); - - try - { - _clients.Add(connection); - } - finally - { - _sync.Release(); - } - } - - public async ValueTask OnMessage(IReactiveConnection connection, IWebsocketFrame message) - { - // JSON sent by the client is deserialized into our record - var received = await message.ReadPayloadAsync(); - - var toSend = received with { Sent = DateTime.UtcNow }; - - await _sync.WaitAsync(); - - try - { - foreach (var client in _clients) - { - // ... and serialized to JSON again - await client.WritePayloadAsync(toSend); - } - } - finally - { - _sync.Release(); - } - } - - public async ValueTask OnClose(IReactiveConnection connection, IWebsocketFrame message) - { - await _sync.WaitAsync(); - - try - { - _clients.Remove(connection); - } - finally - { - _sync.Release(); - } - - await connection.CloseAsync(); - } - - } - - private const string ClientPage = - """ - - - - - Chat - - -
    - - - -
    -
      - - - - """; - -} diff --git a/README.md b/README.md index 78f17de85..1781f6cda 100644 --- a/README.md +++ b/README.md @@ -45,8 +45,8 @@ Running this snippet will provide the following endpoints: ## Samples -The [playground](./Playground/) project provides a quick starting point to view sample code and find more complex apps -built with GenHTTP. See [the documentation](https://genhttp.org/documentation/content/) for all available capabilities. +The [playground](https://genhttp.org/playground/) on the website shows sample code for the frameworks, handlers and +concerns of GenHTTP and lets you send requests to the samples as they run live. See [the documentation](https://genhttp.org/documentation/content/) for all available capabilities. ## Engines From 6d0286b681d01b28482004b7d4aa55b4f3feecd6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andreas=20N=C3=A4geli?= Date: Wed, 11 Nov 2026 17:13:34 +0100 Subject: [PATCH 3/4] chore(playground): Link the samples at their new address on the website Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016Z4d2Q4o4JhUDoAL6Zkxe9 --- AGENTS.md | 2 +- Playground/README.md | 6 +++--- README.md | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index b3627b30f..a93d95786 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -49,7 +49,7 @@ cd Playground && dotnet run # minimal app on http | `Testing/Acceptance` | The test suite. Folder structure mirrors `API/`, `Engine/`, `Modules/`, `Adapters/`. | | `Benchmarks/` | BenchmarkDotNet micro-benchmarks. | | `Packages/` | Meta-package `.nuspec` files (`GenHTTP.Core`, `GenHTTP.Full`, and per-engine variants). | -| `Playground/` | A minimal app for manual checks. The samples for users are on the website (genhttp.org/playground). | +| `Playground/` | A minimal app for manual checks. The samples for users are on the website (genhttp.org/samples). | The parser (Glyph11) and ioxide are separate projects consumed as NuGet packages. If they are checked out next to this repository (`../Glyph11`, `../ioxide`), read their source rather than guessing. Flag diff --git a/Playground/README.md b/Playground/README.md index 2f078433d..91245ffd9 100644 --- a/Playground/README.md +++ b/Playground/README.md @@ -12,8 +12,8 @@ The app is then served at http://localhost:8080/. ## Samples -Samples for the frameworks, handlers and concerns of GenHTTP can be found in the -[playground on the website](https://genhttp.org/playground/), where you can read their -code and send requests to them as they run live. +Samples for the frameworks, handlers and concerns of GenHTTP can be found +[on the website](https://genhttp.org/samples/), where you can read their code and +send requests to them as they run live. The [Ioxide](./Samples/Ioxide/README.md) folder contains samples for the io_uring based engine. diff --git a/README.md b/README.md index 1781f6cda..2dd6c7fc4 100644 --- a/README.md +++ b/README.md @@ -45,8 +45,8 @@ Running this snippet will provide the following endpoints: ## Samples -The [playground](https://genhttp.org/playground/) on the website shows sample code for the frameworks, handlers and -concerns of GenHTTP and lets you send requests to the samples as they run live. See [the documentation](https://genhttp.org/documentation/content/) for all available capabilities. +The [samples](https://genhttp.org/samples/) on the website show the frameworks, handlers and concerns of GenHTTP as +complete programs, and let you send requests to them as they run live. See [the documentation](https://genhttp.org/documentation/content/) for all available capabilities. ## Engines From c9db0b2ed0a71f527e23b2b1360f39d5f832e034 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andreas=20N=C3=A4geli?= Date: Thu, 12 Nov 2026 09:06:44 +0100 Subject: [PATCH 4/4] Add Agentic Coding section to README Added a section on Agentic Coding to explain GenHTTP's modular design and its suitability for AI agents. --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 2dd6c7fc4..d6041bda8 100644 --- a/README.md +++ b/README.md @@ -48,6 +48,10 @@ Running this snippet will provide the following endpoints: The [samples](https://genhttp.org/samples/) on the website show the frameworks, handlers and concerns of GenHTTP as complete programs, and let you send requests to them as they run live. See [the documentation](https://genhttp.org/documentation/content/) for all available capabilities. +## Agentic Coding + +GenHTTP’s modules are decoupled and wired together explicitly, with no hidden magic, so every part of an application can be understood by reading its code. This makes GenHTTP a strong fit for agentic coding in C#, where AI agents can reliably understand, change and extend projects without unexpected side effects. + ## Engines GenHTTP runs on different runtime implementations that can simply be switched by changing a single nuget package