![]() |
Starting an HTTP server is easy. Simply create the zeep::http::server
object, bind
it to an address and call run specifying how many threads to run simultaneously.
Something like this:
#include <zeep/http/server.hpp> int main() { zeep::http::server srv; srv.bind("localhost", 8080); srv.run(2); return 0; }
Running this code will create a server that listens to port 8080 on localhost
and will return NOT FOUND
for all requests. Not particularly
useful of course. It is possible to derive a class from zeep::http::server
and implement handle_request
.
But there is a better alternative: use controllers.
A zeep::http::server
can have one or more controllers. Each controller handles requests that have
URI's that start with a specified prefix. In this example we have a controller
that handles any request, since it has a prefix that is effectively the same
as the root. It returns a simple reply.
#include <zeep/http/server.hpp> #include <zeep/http/controller.hpp> class hello_controller : public zeep::http::controller { public:hello_controller() : controller("/") {} bool handle_request(zeep::http::request& req, zeep::http::reply& rep) {
rep = zeep::http::reply::stock_reply(zeep::http::ok); rep.set_content("Hello", "text/plain"); return true; } }; int main() { zeep::http::server srv; srv.add_controller(new hello_controller()); srv.bind("localhost", 8080); srv.run(2); return 0; }
Specify the root path as prefix, will handle any request URI |
|
Construct a simple reply with status OK (200) and content string |
Still a not so useful example. Fortunately there are several implementations
of controller
that we can use.