Http call with rocket framework and hyper


#1

I’m trying to learn rust and rocket. I wanted to build a small project, which make a http call to an external server.

I haven’t found any documentation to do that in rocket. So i choose the hyper lib. Added it in my Cargo.toml and read the documentation for the client section in the hyper docs.

This is my main function

fn main() {
    let client = Client::new();

    let uri = "http://httpbin.org/ip".parse().unwrap();

    client
        .get(uri)
        .map(|res| {
            println!("Response: {}", res.status());
        })
        .map_err(|err| {
            println!("Error: {}", err);
        });
}

If i run this code, there are no prints in my console, except

   |
55 | /     client
56 | |         .get(uri)
57 | |         .map(|res| {
58 | |             println!("Response: {}", res.status());
...  |
61 | |             println!("Error: {}", err);
62 | |         });
   | |___________^
   |
   = note: #[warn(unused_must_use)] on by default
   = note: futures do nothing unless polled

And what do i need to get this to work on rocket?

#[get("/api")]
fn test() -> ??? <-- what is the type? {
   ??? <-- how can i return the json data here?
}

#2

Rocket is a framework for http servers, not clients.

“futures do nothing unless polled” - The futures won’t execute code unless their “poll” method is called to update their state. Use tokio or hyper::rt to execute the task

fn main() {
    let client = hyper::Client::new();

    let uri = "http://httpbin.org/ip".parse().unwrap();

    let task = client
        .get(uri)
        .map(|res| {
            println!("Response: {}", res.status());
        })
        .map_err(|err| {
            println!("Error: {}", err);
        });
    hyper::rt::run(task); // you can use hyper::rt::spawn too
}