When I use ByteStream, how should I add custom headers? #2776
Replies: 1 comment 1 reply
-
A logical stream cannot have a length. This is a restriction of the HTTP spec, though not a limitation; logically, streams are not necessarily finite, so a length is not applicable. I believe you're using the wrong type for your use-case here, one governed by this restriction when such a thing isn't needed. Everything in Rocket is streamed. The stream can have a known size or an unknown size. The Concretely, this means you can implement a simple struct ProxyStream(SomeStreamType);
impl<'r> Responder<'r, 'static> for ProxyStream {
fn respond_to(self, _: &'r Request<'_>) -> response::Result<'static> {
Response::build()
.sized_body(some_length, self.0)
.finalize();
}
} This assumes that Then return a value of this type from your handler: #[rocket::get("/proxy/<_..>")]
fn handle_proxy(proxyreq: ProxyReq) -> Result<ProxyStream, (Status, String)> {
let (url, host) = proxyreq;
if !check_domain_is_allowed(&url, &host) {
return Err((Status::BadRequest, "url is not allowed".to_owned()));
}
reqwest::get(&url)
.await
.map(ProxyStream)
.map_err(|e| (Status::BadRequest, e.to_string()))
} |
Beta Was this translation helpful? Give feedback.
-
When I use ByteStream, how should I add headers? I'm trying to implement reverse proxy functionality with Rocket, allowing users to stream downloads by passing a URL parameter. My current code is as follows:
It appears to be running fine so far. The only issue is that there is no Content-Length field in the response header, so the download progress cannot be displayed on the browser side. I want to retrieve the Content-Length field from the proxy_resp header and add it to the response header. However, I'm not sure how to do that. I tried using Responser, but without success.
Beta Was this translation helpful? Give feedback.
All reactions