Getting Started
Pistache
is a web framework written in Modern C++ that focuses on performance and provides an elegant
and asynchronous API.
#include "pistache/pistache.h"
Requirements
git is needed to retrieve the sources. Compiling the sources will require
CMake to generate Makefile and a recent version of g++
(at least 4.7).
Also, Pistache
does not support Windows yet.
Installing Pistache
To download the latest available release, clone the repository over github.
git clone https://github.com/oktal/pistache.git
Then, init the submodules:
git submodule update --init
Now, compile the sources:
cd pistache
mkdir build
cd build
cmake -G "Unix Makefiles" -DCMAKE_BUILD_TYPE=Release ..
make
sudo make install
Optionally, you can also run the tests:
make test
Be patient, async_test
can take some time before completing.
And that’s it, now you can start playing with your newly installed Pistache
framework.
Serving requests
Include
First, let’s start by including the right header
#include "pistache/endpoint.h"
Hello World
Requests received by Pistache
are handled with an Http::Handler
.
Let’s start by defining a simple HelloHandler
:
using namespace Net;
class HelloHandler : public Http::Handler {
public:
HTTP_PROTOTYPE(HelloHandler)
void onRequest(const Http::Request& request, Http::ResponseWriter response) {
response.send(Http::Code::Ok, "Hello, World");
}
};
Handlers must inherit the Http::Handler
class and at least define the onRequest
member function.
They must also define a clone()
member function. Simple handlers can use the special HTTP_PROTOTYPE
macro, passing in the name of the class. The macro will take care of defining the clone()
member function
for you.
Final touch
After defining the handler, the server can now be started:
int main() {
Net::Address addr(Net::Ipv4::any(), Net::Port(9080));
auto opts = Http::Endpoint::options().threads(1);
Http::Endpoint server(addr);
server.init(opts);
server.setHandler(std::make_shared<HelloHandler>());
server.serve();
}
For simplicity, you can also use the special listenAndServe
function that will automatically create an
endpoint and instantiate your handler:
int main() {
Http::listenAndServe<HelloHandler>("*:9080");
}
Note that by default, listenAndServe
will only use 1 thread. You can tweak that by passing an Options
argument
to the function:
Http::listenAndServe<HelloHandler>("*:9080", opts);
And that’s it, now you can fire up your favorite curl request and observe the final result:
curl http://localhost:9080/
Hello, World
Complete code for this example can be found on Github: examples/hello_server.cc