首页 > 解决方案 > microsoft cpprestsdk 用相同的 ip 监听多个 url?

问题描述

我想使用cpprestsdk制作一个宁静的 API,我从这里复制了一些代码:

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

现在我不仅要听“ http://0.0.0.0:9080/demo/work1 ”,还要听“ http://0.0.0.0:9080/demo/work2”、“http://0.0.0.0:9080/realfunction/work1 "。都在相同的IP和端口,但不同的子路径

我应该使用多个侦听器在多线程中一一处理所有网址吗?或者还有其他方法可以处理这个吗?

标签: cpprest-sdk

解决方案


你可以设置

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

然后在处理程序中检查请求。在 cpprestsdk 的 github 中链接的示例中,我看到了类似

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

    }
}

推荐阅读