知识卡片
按字节发送HTTP响应
构造 HTTP/1.1 响应时先写协议版本、状态码等状态行,再写头字段与空行,随后放响应体。返回文本文件时,Content-Length 表示响应体的字节数,应和真正发送的字节长度一致。用 stream.write_all(response.as_bytes()) 写出全部字节或得到错误。
相关卡片 [[读懂请求行与头部边界]]
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- 最终项目:构建多线程 Web 服务器 Reading the Request · 查看原书依据
use std::{ ❶ fs, io::{prelude::*, BufReader}, net::{TcpListener, TcpStream}, }; --snip-- fn handle_connection(mut stream: TcpStream) { let buf_reader = BufReader::new(&mut stream); let http_request: Vec<_> = buf_reader .lines() .map(|result| result.unwrap()) .take_while(|line| !line.is_empty()) .collect(); let status_line = "HTTP/1.1 200 OK"; let contents = fs::read_to_string("hello.html").unwrap(); let length = contents.len(); ❷ let response = format!( "{status_line}\r\n\ Content-Length: {length}\r\n\r\n\ {contents}" ); stream.write_all(response.as_bytes()).unwrap(); }