Move / redirect handling to C

This commit is contained in:
2024-05-05 15:24:15 -04:00
parent 5fdd461159
commit c7ab5447ea
5 changed files with 174 additions and 36 deletions

View File

@ -67,6 +67,7 @@ typedef struct _tf_http_connection_t
typedef struct _tf_http_handler_t
{
const char* pattern;
bool is_wildcard;
tf_http_callback_t* callback;
tf_http_cleanup_t* cleanup;
void* user_data;
@ -127,12 +128,43 @@ static void _http_allocate_buffer(uv_handle_t* handle, size_t suggested_size, uv
*buf = uv_buf_init(connection->incoming, sizeof(connection->incoming));
}
static bool _http_pattern_matches(const char* pattern, const char* path, bool is_wildcard)
{
if (!pattern || !*pattern || (!is_wildcard && strcmp(path, pattern) == 0))
{
return true;
}
if (is_wildcard)
{
int i = 0;
int j = 0;
while (pattern[i] && path[j] && pattern[i] != '*' && pattern[i] == path[j])
{
i++;
j++;
}
if (pattern[i] == '*')
{
for (; path[j]; j++)
{
if (_http_pattern_matches(pattern + i + 1, path + j, strchr(pattern + i + 1, '*') != NULL))
{
return true;
}
}
}
return !pattern[i] && !path[j];
}
return false;
}
static bool _http_find_handler(tf_http_t* http, const char* path, tf_http_callback_t** out_callback, const char** out_trace_name, void** out_user_data)
{
for (int i = 0; i < http->handlers_count; i++)
{
if (!http->handlers[i].pattern || !*http->handlers[i].pattern || strcmp(path, http->handlers[i].pattern) == 0 ||
(*http->handlers[i].pattern && strncmp(path, http->handlers[i].pattern, strlen(http->handlers[i].pattern)) == 0 && path[strlen(http->handlers[i].pattern) - 1] == '/'))
if (_http_pattern_matches(http->handlers[i].pattern, path, http->handlers[i].is_wildcard))
{
*out_callback = http->handlers[i].callback;
*out_trace_name = http->handlers[i].pattern;
@ -694,6 +726,7 @@ void tf_http_add_handler(tf_http_t* http, const char* pattern, tf_http_callback_
http->handlers = tf_resize_vec(http->handlers, sizeof(tf_http_handler_t) * (http->handlers_count + 1));
http->handlers[http->handlers_count++] = (tf_http_handler_t) {
.pattern = tf_strdup(pattern),
.is_wildcard = pattern && strchr(pattern, '*') != NULL,
.callback = callback,
.cleanup = cleanup,
.user_data = user_data,