cpr icon indicating copy to clipboard operation
cpr copied to clipboard

Add generic request function in api.h

Open GitSparTV opened this issue 1 year ago • 0 comments
trafficstars

Provides generic function to call any HTTP method.

This helps to avoid such code on your side:

template<class ...Ts>
cpr::Response MakeRequest(std::string_view method, Ts&& ...ts) { // could be enum, string, or bool. Whatever what you use to select different HTTP method
    if (method == "GET") {
        return cpr::Get(std::forward<Ts>(ts)..., cpr::Header{{"Authorization", "token"}});
    else if (method == "POST") {
        return cpr::Post(std::forward<Ts>(ts)..., cpr::Header{{"Authorization", "token"}});
    } else {
        // and so on...
    }
}

Now you can do this:

    template <cpr::HTTPMethod method, typename... Args>
    cpr::Response MakeRequest(Args&&... args) {
        return cpr::Request<method>(std::forward<Args>(args)..., cpr::Header{{"Authorization", "token"}});
    }

and call it like this:

cpr::Response r = MakeRequest<cpr::HTTPMethod::kPost>(cpr::Url{"http://www.httpbin.org/post?a=b"}, cpr::Body{"{\"a\": true}"});

Ideas before the merge:

  • Do we need tests for this function?
  • This function can replace all existing functions like Post(), Get(), and other! Should I refactor it?
  • HTTPMethod doesn't have Download since it's not a method. Do we need it?
  • Do we need Async and/or Multi versions?

Resolves #1117

GitSparTV avatar Sep 30 '24 15:09 GitSparTV