How do you use HttpRequest data? #1824
-
|
What is a simple code example that prints out the contents of a header value with actix-web? #[get("/header")]
async fn print_header(req: HttpRequest) -> impl Responder {
// This is fine
let some_header = req.headers().get("x-some-header").unwrap().to_str().unwrap();
// This triggers a compilation error
some_header
}This snippet brings complaints from the compiler about lifetimes and req getting dropped prematurely. Unfortunately there's nothing in the docs in the way of examples for this fairly common use case. Nothing in cursory Google searches either that demonstrate a simple code example. |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 3 replies
-
|
This is how lifetime works in Rust. Your If you are still confused with how Rust's borrow checker work it best to start with The book For this specific case, |
Beta Was this translation helpful? Give feedback.
-
|
Yea Ikr. People would complain even when you try to help. |
Beta Was this translation helpful? Give feedback.
-
|
Yea. It's my bad to not including an easy answer and our maintainer added that. |
Beta Was this translation helpful? Give feedback.
This is how lifetime works in Rust.
Your
some_headeris referencing theHttpRequestwhich is owned by yourprint_headerfunction.When the function is end
HttpRequestis dropped and it's memory is not valid anymore.If you are still confused with how Rust's borrow checker work it best to start with The book
For this specific case,
some_headeris a&strand it needs to be aStringto return it. So use.to_owned().