how to parse http request in c++

后端 未结 4 1887
梦如初夏
梦如初夏 2021-02-09 01:01

I\'m trying to write a small c++ webserver which handles GET, POST, HEAD requests. My problem is I don\'t know how to parse the headers, message body, etc. It\'s listening on th

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-09 02:02

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

提交回复
热议问题