C++ — 使用C++架設Rest server 番外篇
Aug 31, 2018 · 7 min read
這篇是剛開始研究Rest Server using C++的過程,後來找到比較適合的是Pistache,可以參考
以下是當時後研究的紀錄
有時候環境的關係,會需要使用C++
所看到微軟有維護一套CPPRestSdk
但可以看到Server也就是Listening的部分還在Beta中,而且從去年2017就沒有修改了
而Rest Server部分有請我們參考restweb
基本只要clone下來,
git clone https://github.com/Meenapintu/Restweb然後再bash中輸入
cmake .注意有一個. ,然後輸入
make就可以完成
run server ./Build/bin/restserver不過可能會發現無法執行,改成
./Build/bin/restserver就可以了,可以看到

並且在瀏覽器會是

結果是一個靜態網頁,找一下程式碼
static/index.html被定義在
master/src/handler.cpp這邊定義了所有的GET / POST / 等等行為
handler::handler(utility::string_t url):m_listener(url){ m_listener.support(methods::GET, std::bind(&handler::handle_get, this, std::placeholders::_1)); m_listener.support(methods::PUT, std::bind(&handler::handle_put, this, std::placeholders::_1)); m_listener.support(methods::POST, std::bind(&handler::handle_post, this, std::placeholders::_1)); m_listener.support(methods::DEL, std::bind(&handler::handle_delete, this, std::placeholders::_1)); }而GET回傳了一個靜態網頁
//// Get Request //void handler::handle_get(http_request message){ ucout << message.to_string() << endl; auto paths = http::uri::split_path(http::uri::decode(message.relative_uri().path())); message.relative_uri().path(); //Dbms* d = new Dbms(); //d->connect(); concurrency::streams::fstream::open_istream(U(“static/index.html”), std::ios::in).then([=](concurrency::streams::istream is) { message.reply(status_codes::OK, is, U(“text/html”)) .then([](pplx::task<void> t) { try{ t.get(); } catch(…){ // } }); }).then([=](pplx::task<void>t) { try{ t.get(); } catch(…){ message.reply(status_codes::InternalError,U(“INTERNAL ERROR “)); } }); return; };最入口為 main.cpp
/master/main.cppblog說明為
而另外有一個是for visual studio的 branch
CPP_CMS
但看起來這套server算是有點陽春,於是參考到另一個CppCMS
http://cppcms.com/wikipp/en/page/cppcms_1x_build
一樣先clone下來
git clone https://github.com/artyom-beilis/cppcms.git cppcms記得先安裝需要的套件
apt install cmakeapt install libpcre3-devapt install zlib1g-devapt install libgcrypt11-devapt install libicu-devapt install python
然後建立資料夾
mkdir buildcd build
之後使用cmake
cmake ..完成後就會產生一些檔案

然後會經歷非常久的build

直到跑完我目前還不知道怎麼啟動(待續)
