2

I'm able to request a PNG file with reqwest which I can save to a file through copy().

I'd like to forward the image as a Rocket response. I don't know how to pass the response contents there.

I tried to use Content(ContentType::PNG, response) but I can't figure out how to match a type that has implemented rocket::response::Responder trait. Rocket can't use the Bytes type returned by response.bytes().

#![feature(proc_macro_hygiene, decl_macro)]

extern crate reqwest;
#[macro_use]
extern crate rocket;

use anyhow::Result;
use reqwest::header::USER_AGENT;
use reqwest::Response;
use rocket::http::ContentType;
use rocket::response::content::Content;

#[get("/")]
fn myroute() -> Result<Content<String>, anyhow::Error> {
    let client = reqwest::blocking::Client::new();

    let response = client.get("https://www.rust-lang.org/static/images/rust-logo-blk.svg")
        .header(USER_AGENT, "rust-reqwest")
        .send()?;

    Ok(Content(ContentType::PNG, response.bytes()))
}

fn rocket() -> rocket::Rocket {
    rocket::ignite()
        .mount("/", routes![myroute])
}

fn main() {
    rocket().launch();
}
[dependencies]
anyhow = "1.0"
rocket = "0.4.2"
reqwest = { version = "0.10.4", features = ["blocking", "json"] }
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
simPod
  • 11,498
  • 17
  • 86
  • 139
  • Your question might be answered by the answers of [How do I read the entire body of a Tokio-based Hyper request?](https://stackoverflow.com/a/43420539/155423). – Shepmaster Mar 23 '20 at 19:04
  • It's hard to answer your question because it doesn't include a [MRE]. We can't tell what crates (and their versions), etc. are present in the code. It would make it easier for us to help you if you try to reproduce your error on the [Rust Playground](https://play.rust-lang.org) if possible, otherwise in a brand new Cargo project, then [edit] your question to include the additional info. There are [Rust-specific MRE tips](//stackoverflow.com/tags/rust/info) you can use to reduce your original code for posting here. Thanks! – Shepmaster Mar 23 '20 at 19:05
  • Thanks for feedback, I have updated the code. Did not find a way to use cargo with Playground though. – simPod Mar 23 '20 at 19:23
  • Those use hyper but I use reqwest. The problem here is that I'm unable to pass body between reqwest and rocket while avoiding its modification without saving it into file. I can use only this API https://docs.rs/reqwest/0.10.4/reqwest/blocking/struct.Response.html#method.copy_to – simPod Mar 23 '20 at 19:55
  • Though I guess the easiest would be to migrate to Hyper. – simPod Mar 23 '20 at 20:04
  • Are you just looking for [`as_bytes`](https://docs.rs/reqwest/0.10.4/reqwest/blocking/struct.Body.html#method.as_bytes) which you can then convert to a `Vec`? – Shepmaster Mar 23 '20 at 20:08
  • @simPod did you find the solution? I need exactly same stuff. – rahoolm Apr 20 '22 at 19:11
  • @rahoolm iirc no with reqwest – simPod Apr 27 '22 at 12:34

0 Answers0