EVHttpServer is just an http server implemented by encapsulating libevent using c++, It provides:
-
Simpler api
-
Use thread pool to handle http requests
-
Support regular matching path
See examples here.
Here is a simple example of using EVHttpServer:
#include "EVHttpServer.h"
#include <iostream>
#include <thread>
#include <signal.h>
static volatile bool g_runFlag = true;
void sighandler(int signum)
{
g_runFlag = false;
}
void func(const EVHttpServer::HttpReq & req, EVHttpServer::HttpRes & res, void * arg)
{
std::cout << req.methodStr() << " " << req.path() << std::endl;
std::cout << req.body() << std::endl;
res.setBody(R"({"status":"OK"})");
res.setCode(200);
}
int main(int argc, const char *argv[])
{
EVHttpServer server;
server.addHandler({EVHttpServer::REQ_POST, "/api/fun"}, func);
server.init(9999);
server.start();
signal(SIGINT, sighandler);
while(g_runFlag)
{
std::this_thread::sleep_for(std::chrono::seconds(2));
}
return 0;
}
Click here to jump to the api documentation generated by doxygen.
The first way is to include the source code in the src directory into your project, and then give libevent's header file path, library path and rpath when compiling.
The second way is to use EVHttpServer compiled as a library.
- Clone the repository
git clone https://github.com/quanqixian/EVHttpServer.git
-
Generate the necessary build files
In this step, the third-party library will be cloned.
cd EVHttpServer
cmake -B build -S . -DCMAKE_INSTALL_PREFIX=/path/to/install -DCMAKE_BUILD_TYPE=Release
- Compile the source code. In this step, third-party libraries, EVHttpServer library, samples, tests will be compiled.
cmake --build build
- Install to system
cmake --install build
Now you can use the EVHttpServer library, include the header file "EVHttpServer.h" in the code, link the libevent library and the EVHttpServer library when compiling.