Hyper: How can I copy the Request or its Body?

Created on 30 Aug 2017  路  6Comments  路  Source: hyperium/hyper

The concat2 (or fold) operation requires consumption the request body. How can I do this and saving the request for other operations? For example:

pub fn foo(request: Request) -> Response {
    let body = request.body();
    let total = body.concat2().wait().unwrap();
    println!("{:?}", total);
    bar(&request)
}

Produces an error:

error[E0382]: use of moved value: `request`
  --> src/controller/user.rs:28:10
   |
25 |     let body = request.body();
   |                ------- value moved here
...
28 |     bar(&request)
   |          ^^^^^^^ value used here after move
   |
   = note: move occurs because `request` has type `hyper::Request`, which does not implement the `Copy` trait

But I can not clone the request or its body.

Most helpful comment

@Thomspoon that does not work; adding the headers fails since:

`` for header in headers.iter() { req_copy.headers_mut().set(header); ^^^ the trait hyper::header::Header is not implemented for hyper::header::HeaderView<'_>``
}

All 6 comments

@XX You probably want Request::deconstruct.

pub fn foo(request: Request) -> Response {
    let (method, uri, version, headers, body) = request.deconstruct();
    let total = body.concat2().wait().unwrap();
    println!("{:?}", total);

    // method, uri, version, and headers are still usable
}

@mehcode Thanks for the help. How can I again construct this request after deconstruction to transfer it to another function?

@XX You could just create a new Hyper::Request using the Request::new method, and construct the remaining information with Request::set_version and Request::set_body. Finally, to add your headers, just utilize Request::header_mut, which returns a mutable header struct for your newly constructed request.

@Thomspoon Thanks. Why does not the Request implement a Clone? Is there any reason for this?

The Request type will be replaced with http::Request eventually, which has better ways of pulling out the body and putting together a new Request without the body.

@Thomspoon that does not work; adding the headers fails since:

`` for header in headers.iter() { req_copy.headers_mut().set(header); ^^^ the trait hyper::header::Header is not implemented for hyper::header::HeaderView<'_>``
}

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Visic picture Visic  路  4Comments

mcseemk picture mcseemk  路  3Comments

FGRibreau picture FGRibreau  路  4Comments

seanmonstar picture seanmonstar  路  3Comments

mrjoe7 picture mrjoe7  路  4Comments