Skip to content

Request Handlers

h@di edited this page Jul 20, 2018 · 5 revisions

As mentioned above, any Route may have some handlers to handle incoming requests. Any request handler should be a class derived from RequestHandler class:

class RequestHandler {
public:
  virtual Response *callback(Request *req) = 0;
};

RequestHandler is a pure abstract class which has only one function: callback which should be overridden.

Serving Static Files

Some useful request handlers or serving static files are provided in library:

  • ShowFile: takes filePath and fileType(MIME type) parameters in it's constructor and serves related file

  • ShowPage: takes a filePath parameter in it's constructor and serves text page, specially an .html page

  • ShowImage: takes a filePath parameter in it's constructor and serves image

Also, you can write your own handlers.

Serving Dynamic Files

You should write your own request handler to server dynamic pages. Your handler should inherits from RequestHandler class and override callback function. callback function take a Request *, which comes from client-side, and give a Response *, which will be send to client-side. You should create an appropriate Response * and return it while overriding this function.

This is an example which serves a dynamic html page:

class RandomNumberHandler : public RequestHandler {
public:
  Response *callback(Request *req) {
    Response *res = new Response;
    res->setHeader("Content-Type", "text/html");
    string body;
    body += "<!DOCTYPE html>";
    body += "<html>";
    body += "<body style=\"text-align: center;\">";
    body += "<h1>AP HTTP</h1>";
    body += "<p>";
    body += "a random number in [1, 10] is: ";
    body += to_string(rand() % 10 + 1);
    body += "</p>";
    body += "</body>";
    body += "</html>";
    res->setBody(body);
    return res;
  }
};

Getting Data from Client-side

To get data from client-side, specially using a POST request, you should write your own handler, too. You should return a Response * as well at the end of callback function. Sometimes you should redirect client to a new address after handling POST request.

Redirection

You may want to redirect client to a new page when handling a request, specially after handling a POST request. Response::redirect(std::string url) is a static function of Response class which returns a Response * which will redirects client to url and can be returned in a RequestHandler::callback.

class LoginHandler : public RequestHandler {
public:
  Response *callback(Request *req) {
    string username = req->getBodyParam("username");
    string password = req->getBodyParam("password");
    // do something with username and password
    return Response::redirect("/");
  }
};

AP HTTP

Clone this wiki locally