From 8b198c58ee93c881cff4fe428a06b0d3df4b3637 Mon Sep 17 00:00:00 2001 From: andrewlalis Date: Sat, 5 Jul 2025 22:03:47 -0400 Subject: [PATCH] Added contextData to request. --- source/handy_http_primitives/builder.d | 18 +++++++++++++++++- source/handy_http_primitives/request.d | 2 ++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/source/handy_http_primitives/builder.d b/source/handy_http_primitives/builder.d index 14a40ee..3ea4ac1 100644 --- a/source/handy_http_primitives/builder.d +++ b/source/handy_http_primitives/builder.d @@ -22,6 +22,7 @@ struct ServerHttpRequestBuilder { string[][string] headers; QueryParameter[] queryParams; InputStream!ubyte inputStream = inputStreamObjectFor(NoOpInputStream!ubyte()); + Object[string] contextData; ref withVersion(HttpVersion httpVersion) { this.httpVersion = httpVersion; @@ -75,6 +76,11 @@ struct ServerHttpRequestBuilder { return withBody(cast(ubyte[]) bodyStr); } + ref withContextData(string key, Object obj) { + this.contextData[key] = obj; + return this; + } + ServerHttpRequest build() { return ServerHttpRequest( httpVersion, @@ -83,12 +89,20 @@ struct ServerHttpRequestBuilder { url, headers, queryParams, - inputStream + inputStream, + contextData ); } } unittest { + class SampleContextData { + string name; + this(string name) { + this.name = name; + } + } + ServerHttpRequest r1 = ServerHttpRequestBuilder() .withUrl("/test-url") .withVersion(HttpVersion.V2) @@ -98,6 +112,7 @@ unittest { .withHeader("Content-Type", "text/plain") .withHeader("Content-Length", "12") .withQueryParam("idx", "42") + .withContextData("name", new SampleContextData("andrew")) .build(); assert(r1.httpVersion == HttpVersion.V2); assert(r1.url == "/test-url"); @@ -109,6 +124,7 @@ unittest { assert(r1.getHeaderAs!string("Content-Type") == "text/plain"); assert(r1.getHeaderAs!ulong("Content-Length") == 12); assert(r1.getParamAs!ulong("idx") == 42); + assert((cast(SampleContextData) r1.contextData["name"]).name == "andrew"); } /** diff --git a/source/handy_http_primitives/request.d b/source/handy_http_primitives/request.d index 4306dc4..cba9f08 100644 --- a/source/handy_http_primitives/request.d +++ b/source/handy_http_primitives/request.d @@ -29,6 +29,8 @@ struct ServerHttpRequest { const QueryParameter[] queryParams; /// The underlying stream used to read the body from the request. InputStream!ubyte inputStream; + /// Any additional data about this request that may be populated during handling. + Object[string] contextData; /** * Gets a header as the specified type, or returns the default value if the