Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add generic request function in api.h #1118

Closed

Conversation

GitSparTV
Copy link

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

Copy link
Member

@COM8 COM8 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@GitSparTV Tanks for this PR! Looks good.
Could you please add a few test (examples) here: https://github.com/libcpr/cpr/tree/master/test

And a bit of documentation here: https://github.com/libcpr/docs

@COM8
Copy link
Member

COM8 commented Dec 18, 2024

@GitSparTV I'm closing this one for now since things are missing. Feel free to reopen in case you want to finish this PR.

@COM8 COM8 closed this Dec 18, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Enhance "template metaprogramming magic" for HTTP methods
2 participants