高性能的 URL 路由C語言開發包:R3

jopen 10年前發布 | 18K 次閱讀 R3 C/C++開發

R3是一個URL路由分發開發庫,擁有較高的性能。采用C語言實現。可將你的路由規則編譯成前綴樹。 在啟動時利用構造前綴樹,你可以高效的分發路線。

Requirement

  • autoconf
  • automake
  • check
  • pcre
  • jemalloc
  • graphviz version 2.38.0 (20140413.2041)
  • pkg-config

Pattern Syntax

/blog/post/{id}      use [^/]+ regular expression by default.
/blog/post/{id:\d+}  use `\d+` regular expression instead of default.

C API

#include <r3.h>

// create a router tree with 10 children capacity (this capacity can grow dynamically)
n = r3_tree_create(10);

int route_data = 3;

// insert the route path into the router tree
r3_tree_insert_pathl(n , "/zoo"       , strlen("/zoo")       , NULL, &route_data );
r3_tree_insert_pathl(n , "/foo/bar"   , strlen("/foo/bar")   , NULL, &route_data );
r3_tree_insert_pathl(n , "/bar"       , strlen("/bar")       , NULL, &route_data );
r3_tree_insert_pathl(n , "/post/{id}" , strlen("/post/{id}") , NULL, &route_data );
r3_tree_insert_pathl(n , "/user/{id:\\d+}" , strlen("/user/{id:\\d+}") , NULL, &route_data );

// let's compile the tree!
r3_tree_compile(n);


// dump the compiled tree
r3_tree_dump(n, 0);

// match a route
node *matched_node = r3_tree_match(n, "/foo/bar", strlen("/foo/bar"), NULL);
matched_node->endpoint; // make sure there is a route end at here.
int ret = *( (*int) matched_node->route_ptr );

按條件路由
// create the match entry for capturing dynamic variables.
match_entry * entry = match_entry_create("/foo/bar");
entry->request_method = METHOD_GET;

// create a router tree with 10 children capacity (this capacity can grow dynamically)
n = r3_tree_create(10);

int route_data = 3;

// define the route with conditions
route *r1 = route_create("/blog/post");
r1->request_method = METHOD_GET | METHOD_POST; // ALLOW GET OR POST

// insert the route path into the router tree
r3_tree_insert_route(n, r1, NULL, &route_data );

r3_tree_compile(n);

node *matched_node = r3_tree_match(n, "/foo/bar", strlen("/foo/bar"), entry);
matched_node->endpoint; // make sure there is a route end at here.

if (matched_node->routes) {
    // find the route with matched condition
    route *c = r3_node_match_route(m, entry);
    c->data; // get the data from matched route
}

項目主頁:http://www.baiduhome.net/lib/view/home/1400461801349

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!