Skip to content

Instantly share code, notes, and snippets.

@aravindavk
Created July 9, 2024 10:21
Show Gist options
  • Save aravindavk/d8cfa9c0aa2714068b1ed3eb7cb14262 to your computer and use it in GitHub Desktop.
Save aravindavk/d8cfa9c0aa2714068b1ed3eb7cb14262 to your computer and use it in GitHub Desktop.
#!/usr/bin/env dub
/+ dub.sdl:
dependency "serverino" version="~>0.7.9"
+/
import std.typecons;
import std.string;
import std.conv;
import serverino;
Nullable!(string[string]) matchedPathParams(string pattern, string path)
{
string[string] params;
// If the pattern and path are matching then
// no need check part by part.
if (pattern == path)
return params.nullable;
// Split the pattern and path into parts
auto patternParts = pattern.strip("/").split("/");
auto pathParts = path.strip("/").split("/");
// Pattern group should match the given path parts
if (patternParts.length != pathParts.length)
return Nullable!(string[string]).init;
// For each pattern parts, if it starts with `:`
// then collect it as path param else path part should
// match the respective part of the pattern.
foreach(idx, p; patternParts)
{
if (p[0] == ':')
params[p[1..$]] = pathParts[idx];
else if(p != pathParts[idx])
return Nullable!(string[string]).init;
}
return params.nullable;
}
bool pathMatch(const(Request) req, string method, string pattern)
{
return (
req.method == method.capitalize.to!(Request.Method) &&
!matchedPathParams(pattern, req.path).isNull
);
}
string[string] pathParams(Request req, string pattern)
{
string[string] params;
auto data = matchedPathParams(pattern, req.path);
if (!data.isNull)
params = data.get;
return params;
}
@endpoint @route!((r) => r.pathMatch("Get", "/api/v1/notes/:id"))
void getNote(Request req, Output res)
{
auto params = req.pathParams("/api/v1/notes/:id");
res.write(params["id"]);
}
mixin ServerinoMain;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment