cpr icon indicating copy to clipboard operation
cpr copied to clipboard

Feature Request: Add method to easily add parameters to what's already in the session

Open Triasmus opened this issue 3 years ago • 1 comments

Is your feature request related to a problem? Please describe. I'm currently implementing a client to communicate with the Binance api. Authentication on Binance involves doing an hmac sha256 hash on the query string and request body and then adding the hash to the query string. I determined that using an Interceptor is the best way to go about this, and here is my intercept function:

  cpr::Response BinanceClient::AuthInterceptor::intercept(cpr::Session& session)
  {
    spdlog::trace("AuthInterceptor");
    auto url = session.GetFullRequestUrl();
    std::string queryStr;
    auto found = url.find('?');
    if (found != std::string::npos)
    {
      queryStr = url.substr(found + 1) + "&";
      url = url.substr(0, found);
    }
    queryStr += "timestamp=" + std::to_string(getTimestamp_ms());
    auto hmac(utils::hmacSha256(queryStr, m_secretKey));
    session.SetParameters({});
    session.SetUrl(cpr::Url{url + "?" + queryStr + "&signature=" + hmac});
    session.SetHeader(cpr::Header{{"X-MBX-APIKEY", m_apiKey}});

    return proceed(session);
  }

As you can see, I have to add the signature and the timestamp in a kinda janky way. Instead of adding the parameter, I instead clear the parameters and I add the signature onto the end of the Url. It works... it's just janky.

Describe the solution you'd like It would be wonderful if there was an AddParameters() method so that instead of clearing the parameters and modifying the Url I could just do session.AddParameters({{"signature", hmac}});. Note: The parameter(s) would need to be added in a way that they are guaranteed to be in the query string in the order in which they're given, so just adding the one parameter would result in it beingat the end of the resultant query string.

Describe alternatives you've considered We could be given access the the Parameters member ourselves, and then cpr::Parameters could be given a method to allow us to add parameters to it.

Additional context Nope.

Triasmus avatar Oct 16 '22 19:10 Triasmus

@Triasmus thanks for taking the time to create such a well written feature request!

I agree, such an option would be a great way to improve usability. Accessing cpr::Parameter directly probably won't be possible since at this point it is already inside libcurl. But one could manipulate the libcurl structure here via a cpr::Session::AddUrlParameter call directly.

COM8 avatar Oct 17 '22 09:10 COM8