143 lines
2.6 KiB
C#
143 lines
2.6 KiB
C#
|
|
namespace MBS.Web;
|
|
|
|
public class WebRoute
|
|
{
|
|
public class WebRouteCollection
|
|
: System.Collections.ObjectModel.Collection<WebRoute>
|
|
{
|
|
|
|
}
|
|
|
|
public string PathTemplate { get; }
|
|
public IWebHandler Handler { get; }
|
|
|
|
public WebRoute(string pathTemplate, IWebHandler handler)
|
|
{
|
|
PathTemplate = pathTemplate;
|
|
Handler = handler;
|
|
}
|
|
|
|
public bool Matches(string pathstr, Dictionary<string, string> variables)
|
|
{
|
|
int i = 0;
|
|
int j = 0;
|
|
bool escape = false;
|
|
bool insideVariable = false;
|
|
|
|
string? varname = null, varvalue = null;
|
|
|
|
while (i < PathTemplate.Length)
|
|
{
|
|
if (PathTemplate[i] == '\\')
|
|
{
|
|
escape = true;
|
|
i++;
|
|
continue;
|
|
}
|
|
|
|
if (!escape && (PathTemplate[i] == '{' || (PathTemplate[i] == '$' && PathTemplate.Length - i > 0 && PathTemplate[i + 1] == '(')))
|
|
{
|
|
insideVariable = true;
|
|
varname = "";
|
|
varvalue = "";
|
|
i++;
|
|
continue;
|
|
}
|
|
else if (!escape && (insideVariable && (PathTemplate[i] == '}' || PathTemplate[i] == ')')))
|
|
{
|
|
insideVariable = false;
|
|
i++;
|
|
continue;
|
|
}
|
|
else
|
|
{
|
|
if (insideVariable)
|
|
{
|
|
varname += PathTemplate[i];
|
|
i++;
|
|
continue;
|
|
}
|
|
else
|
|
{
|
|
if (PathTemplate[i] == pathstr[j])
|
|
{
|
|
// yay, we match
|
|
// save the last-known variable, if any...
|
|
if (varname != null && varvalue != null)
|
|
{
|
|
variables[varname] = varvalue;
|
|
|
|
// don't forget to reset it
|
|
varname = null;
|
|
varvalue = null;
|
|
}
|
|
|
|
// ... and keep going
|
|
i++;
|
|
j++;
|
|
|
|
if (i > PathTemplate.Length - 1 || j > pathstr.Length - 1)
|
|
{
|
|
if (i > PathTemplate.Length - 1 && j > pathstr.Length - 1)
|
|
{
|
|
// full match with no path vars
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
}
|
|
else
|
|
{
|
|
// no match
|
|
if (varname != null)
|
|
{
|
|
if (j + 1 < pathstr.Length)
|
|
{
|
|
// we are currently reading a variable value
|
|
varvalue += pathstr[j];
|
|
j++;
|
|
}
|
|
else
|
|
{
|
|
// don't even question it, just return false since we should never reach this point
|
|
return false;
|
|
}
|
|
continue;
|
|
}
|
|
else
|
|
{
|
|
// we do not match!
|
|
return false;
|
|
}
|
|
|
|
if (varvalue != null)
|
|
{
|
|
// we are in a variable
|
|
varvalue += pathstr[j];
|
|
j++;
|
|
continue;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
escape = false;
|
|
}
|
|
|
|
if (varvalue != null && j < pathstr.Length)
|
|
{
|
|
while (j < pathstr.Length)
|
|
{
|
|
varvalue += pathstr[j];
|
|
j++;
|
|
}
|
|
|
|
variables[varname] = varvalue;
|
|
varname = null;
|
|
varvalue = null;
|
|
}
|
|
return true;
|
|
}
|
|
}
|