cpprest-sdk

microsoft cpprestsdk listen to multiple url with same ip?


I want to use cpprestsdk to make a restful API, I copied some code from here :

int main()
{
    http_listener listener("http://0.0.0.0:9080/demo/work1");
    cout<<"start server!"<<endl;
    listener.support(methods::GET,  handle_get);
    listener.support(methods::POST, handle_post);
    listener.support(methods::PUT,  handle_put);
    listener.support(methods::DEL,  handle_del);

    try
    {
        listener
                .open()
                .then([&listener]() {TRACE(L"\nstarting to listen\n"); })
                .wait();

        while (true);
    }
    catch (exception const & e)
    {
        cout << e.what() << endl;
    }

    return 0;
}

now I have to listen to not only "http://0.0.0.0:9080/demo/work1" , but also "http://0.0.0.0:9080/demo/work2", "http://0.0.0.0:9080/realfunction/work1". All in the same IP and port, but different sub-path

Should I use multiple listener to handle all the url one by one in multi-thread? Or there is any other way to handle this?


Solution

  • You can set

    http_listener listener("http://0.0.0.0:9080/");
    

    And then in the handler check the request. In the examples linked in cpprestsdk's github I saw things like

    void handle_get(http_request message) {
        auto path = uri::split_path(uri::decode(message.relative_uri().path()));
    
        if (path.size() == 2 && path[0] == "demo" && path[1] == "work1") {
               // ...
        } else if (path.size() == 2 && path[0] == "demo" && path[1] == "work2") {
              // ...
        } else {
              message.reply(status_codes::NotFound);
    
        }
    }