Added function and delegate constructor functions for HttpRequestHandler, and more tests.
Build and Test Module / build-and-test (push) Successful in 6s Details

This commit is contained in:
Andrew Lalis 2025-03-05 19:27:26 -05:00
parent 262947110f
commit 5fbe682749
3 changed files with 49 additions and 1 deletions

View File

@ -8,5 +8,40 @@ import handy_http_primitives.response;
* incoming HTTP request.
*/
interface HttpRequestHandler {
/**
* Invoked to handle an incoming HTTP request. Implementations should read
* information from the request, and write to the response.
* Params:
* request = The request that was sent by a client.
* response = The response that will be sent back to the client.
*/
void handle(ref ServerHttpRequest request, ref ServerHttpResponse response);
/**
* Gets a request handler that invokes the given function.
* Params:
* fn = The function to invoke when handling requests.
* Returns: The request handler.
*/
static HttpRequestHandler of(void function(ref ServerHttpRequest, ref ServerHttpResponse) fn) {
return new class HttpRequestHandler {
override void handle(ref ServerHttpRequest request, ref ServerHttpResponse response) {
fn(request, response);
}
};
}
/**
* Gets a request handler that invokes the given delegate.
* Params:
* dg = The delegate to invoke when handling requests.
* Returns: The request handler.
*/
static HttpRequestHandler of(void delegate(ref ServerHttpRequest, ref ServerHttpResponse) dg) {
return new class HttpRequestHandler {
override void handle(ref ServerHttpRequest request, ref ServerHttpResponse response) {
dg(request, response);
}
};
}
}

View File

@ -170,6 +170,11 @@ unittest {
assert(parseQueryParameters("test?test") == [QueryParameter("test", [""])]);
// Test parameter without a name.
assert(parseQueryParameters("test?=value") == [QueryParameter("", ["value"])]);
// Test URI-encoded parameter value.
assert(parseQueryParameters(
"test?key=this%20is%20a%20long%20sentence%21%28test%29") ==
[QueryParameter("key", ["this is a long sentence!(test)"])]
);
}
/**
@ -186,3 +191,11 @@ private ptrdiff_t indexOf(string s, char c, size_t offset = 0) {
}
return -1;
}
unittest {
assert(indexOf("test", 't', 0) == 0);
assert(indexOf("test", 't', 1) == 3);
assert(indexOf("", 't', 0) == -1);
assert(indexOf("test", 't', 100) == -1);
assert(indexOf("test", 'a', 0) == -1);
}

View File

@ -1,6 +1,6 @@
module handy_http_primitives.response;
import streams;
import streams : OutputStream;
import handy_http_primitives.multivalue_map;