项目作者: includeos

项目描述 :
IncludeOS C++ Web Application Framework
高级语言: C++
项目地址: git://github.com/includeos/mana.git
创建时间: 2016-09-27T08:24:01Z
项目社区:https://github.com/includeos/mana

开源协议:

下载


mana

IncludeOS C++ Web Application Framework

Acorn is a web server built with Mana which demonstrates a lot of its potential.

Some insight in the implementation of mana can be found in this post.

Usage

It’s easy to get started - check out the examples.

  1. using namespace mana;
  2. using namespace std::string_literals;
  3. std::unique_ptr<Server> server;
  4. void Service::start(const std::string&)
  5. {
  6. Router router;
  7. // GET /
  8. router.on_get("/", [](auto, auto res) {
  9. res->add_body("<html><body><h1>Simple example</h1></body></html>"s);
  10. res->send();
  11. });
  12. server = std::make_unique<Server>(net::Inet4::stack());
  13. server->set_routes(router).listen(80);
  14. }

Routes

Routes is where the server end-points are defined.

  1. Router router;
  2. // GET /
  3. router.on_get("/", [] (auto req, auto res) {
  4. // Serve index.html
  5. });
  6. // POST /users
  7. router.on_post("/users", [] (auto req, auto res) {
  8. // Register new user
  9. });
  10. server.set_routes(router);

There is also support for named parameters in routes.

  1. // GET /users/:id
  2. router.on_get("/users/:id(\\d+)", [](auto req, auto res) {
  3. auto id = req->params().get("id");
  4. // Do actions according to "id"
  5. if(id == "42")
  6. // ...
  7. });

Middleware

Middleware are tasks which are executed before the user code defined in routes.

  1. // Declare a new middleware
  2. class MyMiddleware : public mana::Middleware {
  3. // ...
  4. };
  5. // Add a middleware object
  6. Middleware_ptr my_mw = std::make_shared<MyMiddleware>();
  7. server.use(my_mw);

It’s also possible to just add a simple task with a lambda.

  1. // Add a middleware lambda
  2. server.use([] (auto req, auto res) {
  3. // My custom middleware function
  4. (*next)(); // Don't forget to call next if no response was sent!
  5. });

Psst, there is already some ready-made middleware for Mana!

Attributes

Attributes is a way to extend the Request object with additional data.

  1. // Declare a new attribute
  2. class MyAttribute : public Attribute {
  3. // ...
  4. };
  5. // Set attribute in middleware
  6. MyMiddleware::process(auto req, auto res, auto next) {
  7. auto attr = std::make_shared<MyAttribute>();
  8. req->set_attribute(attr);
  9. (*next)();
  10. }
  11. // Use attribute in route
  12. router.use("/my-route", [] (auto req, auto res) {
  13. if(auto attr = req->get_attribute<MyAttribute>()) {
  14. // Do things with "attr"
  15. }
  16. });