libcpr / cpr

C++ Requests: Curl for People, a spiritual port of Python Requests.
https://docs.libcpr.org/
Other
6.49k stars 922 forks source link

Share data between curl easy handles in easy mode #1057

Open Romantic-LiXuefeng opened 4 months ago

Romantic-LiXuefeng commented 4 months ago

Is your feature request related to a problem?

Share connection cache and dns cache to improve the http requests in easy mode. (eg: HLS media playback)

Possible Solution

libcurl has a generic "sharing interface", where the application creates a "share object" that then holds data that can be shared by any number of easy handles.

Alternatives

No response

Additional Context

No response

COM8 commented 4 months ago

@Romantic-LiXuefeng thanks for the feature request. This sounds like an interesting feature. There is no plan for adding this in the immediate future. But here is a workaround for until we add real support for it:

#include "cpr/curlholder.h"
#include "cpr/session.h"
#include <cassert>
#include <memory>
#include <cpr/cpr.h>
#include <cpr/ssl_options.h>
#include <cpr/threadpool.h>

int main() {
    // Setup curl share
    CURLSH* share = curl_share_init();
    curl_share_setopt(share, CURLSHOPT_SHARE, CURL_LOCK_DATA_COOKIE);
    curl_share_setopt(share, CURLSHOPT_SHARE, CURL_LOCK_DATA_DNS);

    // Create first session
    cpr::Session session1;
    std::shared_ptr<cpr::CurlHolder> holder1 = session1.GetCurlHolder();
    CURL* curl1 = holder1->handle;

    // Create second session
    cpr::Session session2;
    std::shared_ptr<cpr::CurlHolder> holder2 = session2.GetCurlHolder();
    CURL* curl2 = holder2->handle;

    // Apply the share to both session
    curl_easy_setopt(curl1, CURLOPT_SHARE, share);
    curl_easy_setopt(curl2, CURLOPT_SHARE, share);

    // Do further stuff..

    return 0;
}