Rust中TcpStream缓冲区仅能读取multipart form data,其他POST请求内容丢失的问题求助
Rust中TcpStream缓冲区仅能读取multipart form data,其他POST请求内容丢失的问题求助
各位好,我现在在搭建一个本地Rust TCP服务器,用本地REST客户端发请求测试,目前只是把读取到的内容输出到控制台。但遇到了一个棘手的问题:只有multipart/form-data类型的POST请求能完整读取到内容,JSON或application/x-www-form-urlencoded格式的请求只能读到请求头,请求体完全拿不到。
我的处理连接的函数代码大概是这样的:
fn handle_connection(mut stream: TcpStream){ let mut buf_reader = BufReader::with_capacity(16384, &mut stream); let mut request_lines = buf_reader.lines().peekable(); let first_request_line = request_lines.next().unwrap().unwrap(); let parts: Vec<&str> = first_request_line[..].split(" ").collect(); if (parts[0] == "POST" && parts[2] == "HTTP/1.1") { let mut buffer_results = HashMap::new(); let mut i = 0; while (request_lines.peek().is_some()){ let newline = request_lines.next().unwrap().unwrap(); let newline_copy = newline.clone(); if newline_copy == "" { continue; } else if newline_copy.contains(":"){ let newline_string = newline_copy.clone().to_string().to_owned(); let newline_str = string_to_static_str(newline_string); let templine: Vec<&str> = (newline_str.split(":")).clone().collect(); let key = templine[0]; let value = templine[1..].join(":"); buffer_results.insert(key, value.clone()); println!("Continuing Stream {}:{}", key, value); } else { let newline_clone = newline_copy.clone().to_string().to_owned(); let i_i = i32_to_static_str(i.clone()); buffer_results.insert(i_i, newline_clone); println!("Continuing Stream {}:{:#?}", i.to_string(), newline_copy.to_string()); } i += 1; } // ... 后续逻辑省略 } }
测试现象
- 当用RESTED客户端发送JSON或application/x-www-form-urlencoded格式的POST请求时,控制台只输出请求头内容,完全看不到请求体的数据:
POST CALL:[ "POST", "/", "HTTP/1.1", ] Continuing Stream Host: 127.0.0.1:7878 Continuing Stream User-Agent: [[User-Agent]] Continuing Stream Accept: HTTP/1.1 Continuing Stream Accept-Language: [[Language]],en;q=0.5 Continuing Stream Accept-Encoding: gzip, deflate, br, zstd Continuing Stream content-type: application/x-www-form-urlencoded Continuing Stream Content-Length: 27 Continuing Stream Origin: moz-extension://[[HASH]] Continuing Stream Connection: keep-alive Continuing Stream Sec-Fetch-Dest: empty Continuing Stream Sec-Fetch-Mode: cors Continuing Stream Sec-Fetch-Site: same-origin Continuing Stream Priority: u=0
- 但切换成multipart/form-data格式时,能正常读取到包括表单数据在内的所有内容:
Continuing Stream content-type: multipart/form-data Continuing Stream 13:"------[[hash]]" Continuing Stream Content-Disposition: form-data; name="my_silly_request" Continuing Stream 15:"void_angel" Continuing Stream 16:"------[[hash]]--"
我尝试过的解决方法
- 把默认的
BufReader::new()换成BufReader::with_capacity(16384, &mut stream),增大缓冲区容量,没有效果 - 手动在循环后额外调用多次
request_lines.next().unwrap().unwrap(),试图读取更多内容,还是拿不到请求体 - 试过直接调用
buffer.read(),但报错说没有数据可读
我猜测是这几种POST请求的传输机制有什么我没注意到的差异,但实在想不通问题出在哪,有没有大佬能帮我分析下?
内容来源于stack exchange
相关产品推荐
相关产品推荐

