← 返回刚才阅读的位置

知识卡片

操作参考卡 · 10651.c · 生成模型:未记录

按字节发送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(); }

    参考来源

    - 位置:《The Rust Programming Language(第2版)》第20章 最终项目:构建多线程 Web 服务器(来源项目 a19c7933-4eda-4176-aebd-30fe7e1ad292,`extracted/The Rust Programming Language(第2版)/_epub-src/c20.xhtml`,块 0078) - 结论依据:清单展示如何将状态行、Content-Length 和 HTML 正文拼接为响应,并通过 write_all 发送。 - 原始内容: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(); }