I am trying to write a simple http server, and I got a problem when parse http request header to a HashMap.
Here is my code:
use std::collections::HashMap;
use std::net::{TcpListener, TcpStream};
#[derive(Debug)]
pub struct Req<'a> {
method: String,
version: String,
path: String,
header: HashMap<&'a str, &'a str>,
raw: &'a String
}
impl<'a> Req<'a> {
pub fn new(mut stream: TcpStream) -> Option<Req<'a>> {
let raw = Req::get_raw_request(stream);
let mut header = Req {
method: String::new(),
version: String::new(),
path: String::new(),
header: HashMap::new(),
raw: &raw
};
header.parse_header(&raw);
Some(header)
}
fn parse_header(&mut self, req_header: &'a String) {
for l in req_header.lines() {
let index = match l.find(": ") {
Some(i) => i,
None => continue
};
self.header.entry(&l[..index]).or_insert(&l[index + 2..]);
}
}
fn get_raw_request(mut stream: TcpStream) -> String {
//parse tcp stream to string
String::from("GET /path HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: keep-alive\r\nAccept: */*\r\nmore header.....")
}
}
fn main() {
let listener = TcpListener::bind("127.0.0.1:3010").unwrap();
for stream in listener.incoming() {
let _ = Req::new(stream.unwrap());
}
}
Error information:
error[E0597]: `raw` does not live long enough
--> test.rs:21:30
|
21 | header.parse_header(&raw);
| ^^^ does not live long enough
22 | Some(header)
23 | }
| - borrowed value only lives until here
|
note: borrowed value must be valid for the lifetime 'a as defined on the impl at 12:1...
--> test.rs:12:1
|
12 | / impl<'a> Req<'a> {
13 | | pub fn new(mut stream: TcpStream) -> Option<Req<'a>> {
14 | | let raw = Req::get_raw_request(stream);
15 | | let mut header = Req {
... |
38 | | }
39 | | }
| |_^
error: aborting due to previous error
I think if I can return a &'a String
from get_raw_request
the problem can be solved, but I don't how.