how to parse http request in c++

后端 未结 4 1899
梦如初夏
梦如初夏 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 01:39

    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.

    0 讨论(0)
  • 2021-02-09 01:42

    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.

    0 讨论(0)
  • 2021-02-09 01:46

    You may want to consider Proxygen, Facebook's C++ HTTP framework. It's open source under a BSD license.

    0 讨论(0)
  • 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, &params);
        srv.start();
        while (true)
            Thread::sleep(1000);
    }
    
    0 讨论(0)
提交回复
热议问题