知识卡片
路由分支只选择差异
简单路由可把请求行映射到一个包含状态行和文件名的元组,再统一读取文件、计算正文长度、组装和写回响应。与在每个路由中重复序列化相比,分支仅保留 200 对 hello.html、404 对 404.html 等变化,公共处理的修订只需发生一次。整行相等是教学约束,完整路由需要独立解析请求。
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- 最终项目:构建多线程 Web 服务器 Validating the Request and Selectively Responding · 查看原书依据
--snip-- fn handle_connection(mut stream: TcpStream) { --snip-- let (status_line, filename) = if request_line == "GET / HTTP/1.1" { ("HTTP/1.1 200 OK", "hello.html") } else { ("HTTP/1.1 404 NOT FOUND", "404.html") }; let contents = fs::read_to_string(filename).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`,块 0105)
- 结论依据:重构后的清单以分支选择二元组、后续统一读写的方式保留了原行为。
- 原始内容:--snip-- fn handle_connection(mut stream: TcpStream) { --snip-- let (status_line, filename) = if request_line == "GET / HTTP/1.1" { ("HTTP/1.1 200 OK", "hello.html") } else { ("HTTP/1.1 404 NOT FOUND", "404.html") }; let contents = fs::read_to_string(filename).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(); }