diff --git a/include/lnm/http/router.h b/include/lnm/http/router.h index 9fbc05b..04956e4 100644 --- a/include/lnm/http/router.h +++ b/include/lnm/http/router.h @@ -8,13 +8,15 @@ typedef struct lnm_http_route lnm_http_route; +typedef struct lnm_http_route_match_segment { + size_t start; + size_t len; +} lnm_http_route_match_segment; + typedef struct lnm_http_route_match { const lnm_http_route *route; lnm_http_method method; - struct { - size_t start; - size_t len; - } key_segments[LNM_HTTP_MAX_KEY_SEGMENTS]; + lnm_http_route_match_segment key_segments[LNM_HTTP_MAX_KEY_SEGMENTS]; } lnm_http_route_match; typedef struct lnm_http_router lnm_http_router; @@ -47,4 +49,7 @@ lnm_http_route_err lnm_http_router_route(lnm_http_route_match *out, lnm_http_method method, const char *path); +lnm_err lnm_http_route_match_get(lnm_http_route_match_segment **out, + lnm_http_route_match *match, const char *key); + #endif diff --git a/src/http/lnm_http_router.c b/src/http/lnm_http_router.c index 6325deb..6f99431 100644 --- a/src/http/lnm_http_router.c +++ b/src/http/lnm_http_router.c @@ -268,3 +268,30 @@ lnm_http_route_err lnm_http_router_route(lnm_http_route_match *out, return __lnm_http_router_route(out, router, method, path, 0, 0); } + +lnm_err lnm_http_route_match_get(lnm_http_route_match_segment **out, + lnm_http_route_match *match, const char *key) { + if (match->route->key_segments == NULL) { + return lnm_err_not_found; + } + + lnm_http_route_segment_trie *trie = match->route->key_segments; + + while (*key != '\0') { + trie = trie->children[(unsigned char)*key]; + + if (trie == NULL) { + return lnm_err_not_found; + } + + key++; + } + + if (!trie->represents_segment) { + return lnm_err_not_found; + } + + *out = &match->key_segments[trie->index]; + + return lnm_err_ok; +} diff --git a/test/routing.c b/test/routing.c index a1d6a05..7cc7aea 100644 --- a/test/routing.c +++ b/test/routing.c @@ -28,6 +28,15 @@ void test_routing_simple() { TEST_CHECK(match.key_segments[0].len == 8); TEST_CHECK(match.key_segments[1].start == 15); TEST_CHECK(match.key_segments[1].len == 9); + + lnm_http_route_match_segment *segment; + TEST_CHECK(lnm_http_route_match_get(&segment, &match, "second") == lnm_err_ok); + TEST_CHECK(segment->start == 15); + TEST_CHECK(segment->len == 9); + TEST_CHECK(lnm_http_route_match_get(&segment, &match, "yuhh") == lnm_err_not_found); + TEST_CHECK(lnm_http_route_match_get(&segment, &match, "hello") == lnm_err_ok); + TEST_CHECK(segment->start == 6); + TEST_CHECK(segment->len == 8); } TEST_LIST = {