how to parse http request in c++
Boost.Asio is a good library but relativel low-level. You’ll really want to use a higher level library. There’s a modern C++ library called node.native which you should check out. A very server can be implemented as follows:
#include <iostream>
#include <native/native.h>
using namespace native::http;
int main() {
http server;
if(!server.listen("0.0.0.0", 8080, [](request& req, response& res) {
res.set_status(200);
res.set_header("Content-Type", "text/plain");
res.end("C++ FTW\n");
})) return 1; // Failed to run server.
std::cout << "Server running at http://0.0.0.0:8080/" << std::endl;
return native::run();
}
It doesn’t get much simpler than this.
Yes, this is basically just string parsing and then the response creating that goes back to the browser, following the specification.
But if this is not just an hobby project and you do not want to take on a really big task you should use either Apache, if you need a web server you need to extend, or tntnet, if you need a c++ web framework, or cpp-netlib if you need C++ network stuff.
Before doing everything yourself, I introduce you Poco:
class MyHTTPRequestHandler : public HTTPRequestHandler
{
public:
virtual void handleRequest(HTTPServerRequest & request,
HTTPServerResponse & response) {
// Write your HTML response in res object
}
};
class MyRequestHandlerFactory : public HTTPRequestHandlerFactory
{
MyHTTPRequestHandler handler;
public:
MyRequestHandlerFactory(){}
HTTPRequestHandler* createRequestHandler(const HTTPServerRequest& request)
{
const string method = request.getMethod();
if (method == "get" || method == "post")
return &handler;
return 0;
}
};
int main()
{
HTTPServerParams params;
params.setMaxQueued(100);
params.setMaxThreads(16);
ServerSocket svs(80);
MyRequestHandlerFactory factory;
HTTPServer srv(&factory, svs, ¶ms);
srv.start();
while (true)
Thread::sleep(1000);
}