Use hyper::Client;

I am using a (keep alive) client in the latest version of hyper, so far making just a single request from it.
I now want to make several requests from it within different functions, so I figured I will create the client in the main and pass it to the functions as an argument:

async fn main() {
     	   let https = HttpsConnector::new().expect("getpr failed to get httpsconnector");
     	   let client = Client::builder()
     		.keep_alive(true)
     		.build::<_, hyper::Body>(https);
      	   let a = getpr(client); 

The problem is I have no idea about the type of the client, needed for the head of the getpr function declaration. Nor am I able to find it.

Look in the docs at the signature of build:

pub fn build<C, B>(&self, connector: C) -> Client<C, B>
where
    C: Connect,
    C::Transport: 'static,
    C::Future: 'static,
    B: Payload + Send,
    B::Data: Send,

There's a lot of noise there from the trait bounds, but what it boils down to is that the type will be Client<C, B>, where C is the type of the connector, and B is the type of the body. We can already tell from looking at your code what these types are in your case - you're using HttpsConnector, and Body.

Therefore, the type of your client should be Client<HttpsConnector, Body>.

Note that this does assume that you'll never want to use your code with other kinds of Client - if you're trying to write a re-usable library, you may want to use generic types for one or both of the type parameters (like build does).

1 Like

Are you sure about that?

async fn getpr(cl:Client<HttpsConnector,Body>) ->

complains saying: expected 1 type argument

Oh whoops, I missed the fact that you're using hyper_tls::HttpsConnector, not hyper::HttpConnector. The former also takes a type parameter, which is the type of the underlying Hyper connector.

HttpsConnector::new gives you a HttpsConnector<HttpConnector>, so your full type would be Client<HttpsConnector<HttpConnector>, Body>.

At that point, it might be worth defining a type alias so you don't have to type that out every time:

type MyClient = Client<HttpsConnector<HttpConnector>, Body>;
1 Like

Thanks, after also adding:

use hyper::client::HttpConnector;

it now compiles!
In case anyone else is interested, it now needs this complete set:

use serde::{Deserialize};
use tokio::{ prelude::*,io, codec };
use futures::try_join;
use hyper::Client;
use hyper::client::HttpConnector;
use hyper::http::Request;
use hyper::body::Body;
use hyper_tls::HttpsConnector;