How to parse an HTTP request in C ++

I am trying to write a small C ++ web server that handles GET, POST, HEAD requests. My problem is that I don’t know how to parse headers, message body, etc. He listens to the socket, I can even write stuff in the browser just fine, but I'm wondering how can I do this in C ++.

Afaik's standard GET / POST request should look something like this:

GET /index HTTP/1.1
Host: 192.168.0.199:80
Connection: keep-alive
Accept: */*
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.22 (KHTML, like Gecko)     Chrome/25.0.1364.97 Safari/537.22
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3

this is the message body

All lines end with '\ r \ n'.

Should I just split the request into "\ n" and trim them (and if so, how)? Also how to process files in post data?

, , - , key = > value, , (, PHP, ) (, ) , '/'.

!

+5
4

, Poco, HTTP-.

- :

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, &params);
    srv.start();
    while (true)
        Thread::sleep(1000);
}
+1

Boost.Asio - , . . Theres - ++ node.native, . :

#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();
}

, .

+3

, Proxygen, Facebook ++. BSD.

+1

, , , , .

But if this is not just a hobby project, and you don’t want to do a really big task, you should use either Apache if you need a web server that you need to expand, or tntnet if you need a C ++ web environment, or cpp-netlib if you need C ++ network stuff.

0
source

All Articles