介绍
R3是一个高性能的URL路由器库,因此,它是用C实现的。它将R3路由路径编译成前缀trie。
通过在启动时构造前缀树,可以高效地将路径分配给控制器。
- github地址
https://github.com/c9s/r3
安装
sudo yum install pcre-devel # 安装 pcre: perl的正则库
mkdir c9s && cd c9s
git clone https://github.com/c9s/r3.git
cd r3
git checkout 2.0
mkdir build && cd build
cmake .. && make && sudo make install
# 在~/.zshrc 或者是 ~/.bashrc 中写明
export PKG_CONFIG_PATH=$PKG_CONFIG_PATH:/usr/lib/pkgconfig:/usr/local/lib/pkgconfig
# source ~/.zshrc 或 source ~/.bashrc后
pkg-config --list-all | grep 'r3' #看看能不能找得到
pkg-config --libs r3 # -L/usr/local/lib -lr3 -lpcre
注:
- spdlog/spdlog.h 与 r3.h 发生了冲突,编译不过。。。
/usr/local/include/spdlog/fmt/bundled/format.h:1817:35: error: inconsistent types ‘int’ and ‘bool’ deduced for lambda return type
第一个程序
// simple_test.cc
#include <cassert>
#include <iostream>
#include <r3.h>
#include <string>
int main(int argc, char *argv[]) {
auto tree_ = r3_tree_create(1024);
std::string home_path_ = "/home/";
std::string page_path_ = "/page/{id:\\d+}";
r3_tree_insert_routel(tree_, METHOD_GET | METHOD_POST, home_path_.c_str(),
home_path_.size(), nullptr);
r3_tree_insert_routel(tree_, METHOD_GET | METHOD_POST, page_path_.c_str(),
page_path_.size(), nullptr);
char *errstr_ = nullptr;
if (r3_tree_compile(tree_, &errstr_)) {
std::cerr << "err!:" << errstr_ << std::endl;
free(errstr_);
return 1;
}
auto entry_ = match_entry_create("/page/11024");
entry_->request_method = METHOD_GET;
auto matched_entry_ = r3_tree_match_route(tree_, entry_);
assert(matched_entry_ != nullptr);
if (matched_entry_->host.len)
std::cout << " matched host: " << matched_entry_->host.base << std::endl;
if (matched_entry_->path.len)
std::cout << " matched path: " << matched_entry_->path.base << std::endl;
if (matched_entry_->remote_addr_pattern.len)
std::cout << " matched remote_addr_pattern: "
<< matched_entry_->remote_addr_pattern.base << std::endl;
match_entry_free(entry_);
r3_tree_free(tree_);
return 0;
}
g++ -o simple_test simple_test.cc -std=c++11 -lpcre -lr3