Skip to content

Creating a New Server

h@di edited this page Jan 10, 2019 · 2 revisions

To create a new server, you should create a new object of Server class. The constructor of Server class has an optional arguments:

  1. int port: specifies on which port server will be listen

After that, You should define some Routes to server and add a POST and/or GET handler to every one of them. You can do this by calling get(std::string path, RequestHandler *handler) and post(std::string path, RequestHandler *handler). Moreover, you can add a handler for not found errors by setNotFoundErrPage(std::string), which its argument is address of .html file which should be served when a request with an invalid address is received.

At last, you should call run() method to start server.

Server will throw a Server::Exception object on failure.

Your main can be like:

int main(int argc, char **argv) {
  try {
    Server server(argc > 1 ? atoi(argv[1]) : 5000);
    server.setNotFoundErrPage("static/404.html");
    server.post("/login", new LoginHandler());  // get data from client-side
    server.get("/rand", new RandomNumberHandler());  // serve dynamic page
    server.get("/home.png", new ShowImage("static/home.png"));  // serve static image
    server.get("/", new ShowPage("static/home.html"));  // serve static page
    server.run();
  } catch (Server::Exception e) {
    cerr << e.getMessage() << endl;
  }
}

AP HTTP

Clone this wiki locally