Posted at

C++用マイクロフレームワーク作ってみた

More than 1 year has passed since last update.

需要は多分ない。

ヘッダオンリーなのでインクルードすれば使えます。

https://github.com/nocotan/otus


依存


Hello World

#include "otus.h"


int main() {
ots::otus app = ots::otus();
app.route("/", "GET", [](ots::request req){
return "Hello, World!";
});

app.run("localhost", "8080");

return 0;
}


htmlレンダラー

#include "otus.h"


int main() {
ots::otus app = ots::otus();
app.route("/", "GET", [](ots::request req){
return ots::render_template("test.html");
});

app.run("localhost", "8080");

return 0;
}


Request

#include "otus.h"

using namespace std;

int main() {
// initialize
ots::otus app = ots::otus();

// routing
app.route("/", "GET", [](ots::request req)->string{
cout << req.method << endl;
cout << req.path << endl;
cout << req.source << endl;
cout << req.destination << endl;
cout << req.body << endl;
for (auto header : req.headers) {
cout << header.name << ":" << header.value << endl;
}
return ots::render_template("test.html");
});

app.route("/", "POST", [](ots::request req)->string{
cout << req.method << endl;
cout << req.path << endl;
cout << req.source << endl;
cout << req.destination << endl;
cout << req.body << endl;
return "OK";
});

app.run("localhost", "9000");

return 0;
}


コンパイル

g++ -std=c++11 test.cpp -I<path to cpp-netlib> -L<path to cpp-netlib/libs/network/src> -lpthread -lboost_system -lboost_thread -lcppnetlib-uri -lcppnetlib-client-connections -lssl -lcrypto