Rust Web 全栈开发(二):构建 HTTP Server

Rust Web 全栈开发(二):构建 HTTP Server

  • Rust Web 全栈开发(二):构建 HTTP Server
    • 创建成员包/库:httpserver、http
    • 解析 HTTP 请求
      • HTTP 请求的构成
      • 构建 HttpRequest
    • 构建 HTTP 响应
      • HTTP 响应的构成
      • 构建 HttpResponse
        • lib

Rust Web 全栈开发(二):构建 HTTP Server

参考视频:https://www.bilibili.com/video/BV1RP4y1G7KF

Web Server 的消息流动图:

在这里插入图片描述

Server:监听 TCP 字节流

Router:接收 HTTP 请求,并决定调用哪个 Handler

Handler:处理 HTTP 请求,构建 HTTP 响应

HTTP Library:

  • 解释字节流,把它转换为 HTTP 请求
  • 把 HTTP 响应转换回字节流

构建步骤:

  1. 解析 HTTP 请求消息
  2. 构建 HTTP 响应消息
  3. 路由与 Handler
  4. 测试 Web Server

创建成员包/库:httpserver、http

在原项目下新建成员包 httpserver、成员库 http:

cargo new httpserver
cargo new --lib http

在这里插入图片描述

在工作区内运行 cargo new 会自动将新创建的包添加到工作区内 Cargo.toml 的 [workspace] 定义中的 members 键中,如下所示:

在这里插入图片描述

在 http 成员库的 src 目录下新建两个文件:httprequest.rs、httpresponse.rs。

此时,我们可以通过运行 cargo build 来构建工作区。项目目录下的文件应该是这样的:

├── Cargo.lock
├── Cargo.toml
├── httpserver
│   ├── Cargo.toml
│   └── src
│       └── main.rs
├── http
│   ├── Cargo.toml
│   └── src
│       └── lib.rs
│       └── httprequest.rs
│       └── httpresponse.rs
├── tcpclient
│   ├── Cargo.toml
│   └── src
│       └── main.rs
├── tcpserver
│   ├── Cargo.toml
│   └── src
│       └── main.rs
└── target

解析 HTTP 请求

HTTP 请求的构成

HTTP 请求报文由 3 部分组成:请求行、请求头、请求体。

在这里插入图片描述

构建 HttpRequest

3 个数据结构:

名称类型描述
HttpRequeststruct表示 HTTP 请求
Methodenum指定所允许的 HTTP 方法
Versionenum指定所允许的 HTTP 版本

以上 3 个数据结构都需要实现的 3 个 trait:

名称描述
From<&str>用于把传进来的字符串切片转换为 HttpRequest
Debug打印调试信息
PartialEq用于解析和自动化测试脚本里做比较

打开 http 成员库中的 httprequest.rs,编写代码:

use std::collections::HashMap;#[derive(Debug, PartialEq)]
pub enum Method {Get,Post,Uninitialized,
}
impl From<&str> for Method {fn from(s: &str) -> Method {match s {"GET" => Method::Get,"POST" => Method::Post,_ => Method::Uninitialized,}}
}#[derive(Debug, PartialEq)]
pub enum Version {V1_1,V2_0,Uninitialized,
}impl From<&str> for Version {fn from(s: &str) -> Version {match s {"HTTP/1.1" => Version::V1_1,_ => Version::Uninitialized,}}
}#[derive(Debug, PartialEq)]
pub enum Resource {Path(String),
}#[derive(Debug)]
pub struct HttpRequest {pub method: Method,pub resource: Resource,pub version: Version,pub headers: HashMap<String, String>,pub body: String,
}impl From<String> for HttpRequest {fn from(request: String) -> HttpRequest {let mut parsed_method = Method::Uninitialized;let mut parsed_resource = Resource::Path("".to_string());let mut parsed_version =  Version::V1_1;let mut parsed_headers = HashMap::new();let mut parsed_body = "";for line in request.lines() {if line.contains("HTTP") {let (method, resource, version) = process_request_line(line);parsed_method = method;parsed_resource = resource;parsed_version = version;} else if line.contains(":") {let (key, value) = process_header_line(line);parsed_headers.insert(key, value);} else if line.len() == 0 {} else {parsed_body = line;}}HttpRequest {method: parsed_method,resource: parsed_resource,version: parsed_version,headers: parsed_headers,body: parsed_body.to_string(),}}
}fn process_header_line(s: &str) -> (String, String) {let mut header_items = s.split(":");let mut key = String::from("");let mut value = String::from("");if  let Some(k) = header_items.next() {key = k.to_string();}if let Some(v) = header_items.next() {value = v.to_string();}(key, value)
}fn process_request_line(s: &str) -> (Method, Resource, Version) {let mut words = s.split_whitespace();let method = words.next().unwrap();let resource = words.next().unwrap();let version = words.next().unwrap();(method.into(),Resource::Path(resource.to_string()),version.into())
}#[cfg(test)]
mod test {use super::*;#[test]fn test_method_into() {let method: Method = "GET".into();assert_eq!(method, Method::Get);}#[test]fn test_version_into() {let version: Version = "HTTP/1.1".into();assert_eq!(version, Version::V1_1);}#[test]fn test_read_http() {let s = String::from("GET /greeting HTTP/1.1\r\nHost: localhost:3000\r\nUser-Agent: curl/7.71.1\r\nAccept: */*\r\n\r\n");let mut headers_excepted = HashMap::new();headers_excepted.insert("Host".into(), " localhost".into());headers_excepted.insert("Accept".into(), " */*".into());headers_excepted.insert("User-Agent".into(), " curl/7.71.1".into());let request: HttpRequest = s.into();assert_eq!(request.method, Method::Get);assert_eq!(request.resource, Resource::Path("/greeting".to_string()));assert_eq!(request.version, Version::V1_1);assert_eq!(request.headers, headers_excepted);}
}

运行命令 cargo test -p http,测试 http 成员库。

3 个测试都通过了:

在这里插入图片描述

构建 HTTP 响应

HTTP 响应的构成

HTTP 响应报文由 3 部分组成:响应行、响应头、响应体。

在这里插入图片描述

构建 HttpResponse

HttpResponse 需要实现的方法或 trait:

名称描述
Default trait指定成员的默认值
From trait将 HttpResponse 转化为 String
new()使用默认值创建一个新的 HttpResponse 结构体
getter 方法获取 HttpResponse 成员变量的值
send_response()构建响应,将原始字节通过 TCP 传送

打开 http 成员库中的 httpresponse.rs,编写代码:

use std::collections::HashMap;
use std::io::{Result, Write};#[derive(Debug, PartialEq, Clone)]
pub struct HttpResponse<'a> {version: &'a str,status_code: &'a str,status_text: &'a str,headers: Option<HashMap<&'a str, &'a str>>,body: Option<String>,
}impl<'a> Default for HttpResponse<'a> {fn default() -> Self {Self {version: "HTTP/1.1".into(),status_code: "200".into(),status_text: "OK".into(),headers: None,body: None,}}
}impl<'a> From<HttpResponse<'a>> for String {fn from(response: HttpResponse) -> String {let res = response.clone();format!("{} {} {}\r\n{}Content-Length: {}\r\n\r\n{}",&res.version(),&res.status_code(),&res.status_text(),&res.headers(),&response.body.unwrap().len(),&res.body(),)}
}impl<'a> HttpResponse<'a> {pub fn new(status_code: &'a str,headers: Option<HashMap<&'a str, &'a str>>,body: Option<String>,) -> HttpResponse<'a> {let mut response: HttpResponse<'a> = HttpResponse::default();if status_code != "200" {response.status_code = status_code.into();}response.status_text = match response.status_code {// 消息"100" => "Continue".into(),"101" => "Switching Protocols".into(),"102" => "Processing".into(),// 成功"200" => "OK".into(),"201" => "Created".into(),"202" => "Accepted".into(),"203" => "Non-Authoritative Information".into(),"204" => "No Content".into(),"205" => "Reset Content".into(),"206" => "Partial Content".into(),"207" => "Multi-Status".into(),// 重定向"300" => "Multiple Choices".into(),"301" => "Moved Permanently".into(),"302" => "Move Temporarily".into(),"303" => "See Other".into(),"304" => "Not Modified".into(),"305" => "Use Proxy".into(),"306" => "Switch Proxy".into(),"307" => "Temporary Redirect".into(),// 请求错误"400" => "Bad Request".into(),"401" => "Unauthorized".into(),"402" => "Payment Required".into(),"403" => "Forbidden".into(),"404" => "Not Found".into(),"405" => "Method Not Allowed".into(),"406" => "Not Acceptable".into(),"407" => "Proxy Authentication Required".into(),"408" => "Request Timeout".into(),"409" => "Conflict".into(),"410" => "Gone".into(),"411" => "Length Required".into(),"412" => "Precondition Failed".into(),"413" => "Request Entity Too Large".into(),"414" => "Request-URI Too Long".into(),"415" => "Unsupported Media Type".into(),"416" => "Requested Range Not Satisfiable".into(),"417" => "Expectation Failed".into(),"421" => "Misdirected Request".into(),"422" => "Unprocessable Entity".into(),"423" => "Locked".into(),"424" => "Failed Dependency".into(),"425" => "Too Early".into(),"426" => "Upgrade Required".into(),"449" => "Retry With".into(),"451" => "Unavailable For Legal Reasons".into(),// 服务器错误"500" => "Internal Server Error".into(),"501" => "Not Implemented".into(),"502" => "Bad Gateway".into(),"503" => "Service Unavailable".into(),"504" => "Gateway Timeout".into(),"505" => "HTTP Version Not Supported".into(),"506" => "Variant Also Negotiates".into(),"507" => "Insufficient Storage".into(),"509" => "Bandwidth Limit Exceeded".into(),"510" => "Not Extended".into(),"600" => "Unparseable Response Headers".into(),_ => "Not Found".into(),};response.headers = match &headers {Some(_h) => headers,None => {let mut header = HashMap::new();header.insert("Content-Type", "text/html");Some(header)}};response.body = body;response}fn version(&self) -> &str {self.version}fn status_code(&self) -> &str {self.status_code}fn  status_text(&self) -> &str {self.status_text}fn headers(&self) -> String {let map = self.headers.clone().unwrap();let mut headers_string = "".into();for (key, value) in map.iter() {headers_string = format!("{headers_string}{}:{}\r\n", key, value);}headers_string}fn body(&self) -> &str {match &self.body {Some(b) => b.as_str(),None => "",}}pub fn send_response(&self, write_stream: &mut impl Write) -> Result<()> {let response = self.clone();let response_string: String = String::from(response);let _ = write!(write_stream, "{}", response_string);Ok(())}
}#[cfg(test)]
mod test {use super::*;#[test]fn test_response_struct_creation_200() {let response_actual = HttpResponse::new("200",None,Some("xxxx".into()),);let response_excepted = HttpResponse {version: "HTTP/1.1",status_code: "200",status_text: "OK",headers: {let mut h = HashMap::new();h.insert("Content-Type", "text/html");Some(h)},body: Some("xxxx".into()),};assert_eq!(response_actual, response_excepted);}#[test]fn test_response_struct_creation_404() {let response_actual = HttpResponse::new("404",None,Some("xxxx".into()),);let response_excepted = HttpResponse {version: "HTTP/1.1",status_code: "404",status_text: "Not Found",headers: {let mut h = HashMap::new();h.insert("Content-Type", "text/html");Some(h)},body: Some("xxxx".into()),};assert_eq!(response_actual, response_excepted);}#[test]fn test_http_response_creation() {let response_excepted = HttpResponse {version: "HTTP/1.1",status_code: "404",status_text: "Not Found",headers: {let mut h = HashMap::new();h.insert("Content-Type", "text/html");Some(h)},body: Some("xxxx".into()),};let http_string: String = response_excepted.into();let actual_string = "HTTP/1.1 404 Not Found\r\nContent-Type:text/html\r\nContent-Length: 4\r\n\r\nxxxx";assert_eq!(http_string, actual_string);}
}

运行命令 cargo test -p http,测试 http 成员库。

现在一共有 6 个测试,都通过了:

在这里插入图片描述

lib

打开 http 成员库中的 lib.rs,编写代码:

pub mod httprequest;
pub mod httpresponse;

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.pswp.cn/news/912949.shtml
繁体地址,请注明出处:http://hk.pswp.cn/news/912949.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

小架构step系列01:小架构初衷

1 概述 小公司做业务服务&#xff0c;需要聚焦到实际的业务上&#xff0c;尽快通过业务服务客户&#xff0c;给客户创建价值&#xff0c;公司才能生存下去。在技术上采用的Web应用架构具备以下特点&#xff1a; 主要由开源组件组装而成。这样既可以节省成本&#xff0c;也可以把…

苹果AR/VR头显路线图曝光,微美全息推进AI/AR智能眼镜新品开启视觉体验篇章

日前&#xff0c;郭明錤发表了一篇关于苹果&#xff08;AAPL.US&#xff09;2025-2028头戴式产品路线图的文章&#xff0c;里面提到苹果正在开发涵盖MR头显、AI眼镜、AR眼镜、Birdbath眼镜等共计7款设备。 苹果的头显设备中&#xff0c;大量出货的产品是类似于Ray-Ban Meta的智…

python pyecharts 数据分析及可视化(2)

一、任务要求 任务二&#xff1a;感冒高发期分析 【任务说明】 感冒是一种常见的急性上呼吸道病毒性感染性疾病&#xff0c;多由鼻病 毒、副流感病毒、呼吸道合胞病毒、埃可病毒、柯萨奇病毒、冠状病 毒、腺病毒等引起。临床表现为鼻塞、喷嚏、流涕、发热、咳嗽、头 痛等&#…

React自学 基础一

React基础 React 是一个由 Facebook&#xff08;现 Meta&#xff09;开发并维护的、开源的 JavaScript 库&#xff0c;主要用于 构建用户界面&#xff08;UI&#xff09;&#xff0c;尤其是单页面应用程序中的动态、交互式界面。 简单示例&#xff1a; import React, { useSt…

PHP语法基础篇(八):超全局变量

超全局变量是在 PHP 4.1.0 中引入的&#xff0c;并且是内置变量&#xff0c;可以在所有作用域中始终可用。 PHP 中的许多预定义变量都是"超全局的"&#xff0c;这意味着它们在一个脚本的全部作用域中都可用。在函数或方法中无需执行 global $variable; 就可以访问它们…

NumPy-核心函数concatenate()深度解析

NumPy-核心函数concatenate深度解析 一、concatenate()基础语法与核心参数函数签名与核心作用基础特性&#xff1a;形状匹配规则 二、多维数组拼接实战示例1. 一维数组&#xff1a;最简单的序列拼接2. 二维数组&#xff1a;按行与按列拼接对比按行拼接&#xff08;垂直方向&…

aws(学习笔记第四十八课) appsync-graphql-dynamodb

aws(学习笔记第四十八课) appsync-graphql-dynamodb 使用graphql来方便操作dynamodb 理解graphql中的graphql api&#xff0c;schema&#xff0c;resolver 学习内容&#xff1a; graphqlgraphql apischemaresolver 1. 代码连接和修改 1.1 代码链接 代码链接&#xff08;app…

关于微前端框架micro,子应用设置--el-primary-color失效的问题

设置了manualChunks导致失效,去掉即可,比较小众的问题 下面是deepseek的分析 关于 manualChunks 导致 Element Plus 主题变量失效的问题 你找到的确实是问题的关键所在。这个 manualChunks 配置影响了 Element Plus 样式和变量的加载顺序&#xff0c;从而导致主题变量失效。…

MySQL 学习 之 你还在用 TIMESTAMP 吗?

目录 1. 弊端1.1. 取值范围1.2. 时区依赖1.3. 隐式转换 2. 区别3. 解决 1. 弊端 1.1. 取值范围 TIMESTAMP 的取值范围为 1970-01-01 00:00:01 UTC 到 2038-01-19 03:14:07 UTC&#xff0c;超出范围的数据会被强制归零或触发异常‌。 具体表现为在基金债券等业务中&#xff0…

java中字节和字符有何区别,为什么有字节流和字符流?

在Java中&#xff0c;字节&#xff08;byte&#xff09;和字符&#xff08;char&#xff09;是两种不同的数据类型&#xff0c;它们的主要区别在于所表示的数据单位、用途以及编码方式,字节流和字符流的区分就是为了解决编码问题。 字节&#xff08;byte&#xff09;&#xff…

伴随矩阵 线性代数

伴随矩阵的定义 伴随矩阵的作用是什么&#xff1f;我们可以看到其伴随矩阵乘上自己等于一个数&#xff08;自身的行列式&#xff09;乘以E&#xff0c;所以对于一个方阵来说&#xff0c;其逆矩阵就是自己的伴随矩阵的倍数。 所以说伴随矩阵的作用就是用来更好的求解逆矩阵的。…

百胜软件获邀走进华为,AI实践经验分享精彩绽放

在数字化浪潮席卷全球的当下&#xff0c;零售行业正经历着深刻变革&#xff0c;人工智能技术成为重塑行业格局的关键力量。6月26日&#xff0c;“走进华为——智领零售&#xff0c;AI赋能新未来”活动在华为练秋湖研发中心成功举办。百胜软件作为数字零售深耕者&#xff0c;携“…

六种扎根理论的编码方法

一、实境编码 1.概念&#xff1a;实境编码是一种基于参与者原生语言的质性编码方法&#xff0c;其核心在于直接采用研究对象在访谈、观察或文本中使用的原始词汇、短语或独特表达作为分析代码。该方法通过保留数据的"原生态"语言形式&#xff08;如方言、隐喻、习惯用…

【Spring篇09】:制作自己的spring-boot-starter依赖1

文章目录 1. Spring Boot Starter 的本质2. Starter 的模块结构&#xff08;推荐&#xff09;3. 制作 xxx-spring-boot-autoconfigure 模块3.1 添加必要的依赖3.2 编写具体功能的配置类3.3 编写自动化配置类 (AutoConfiguration)3.4 注册自动化配置类 (.imports 或 spring.fact…

Qt6之qml自定义控件开发流程指南

Qt6之qml自定义控件开发流程指南 &#x1f6e0;️ 一、基础控件创建 定义 QML 文件 在工程中新建 QML 文件&#xff08;如 CustomButton.qml&#xff09;&#xff0c;文件名首字母大写。 使用基础组件&#xff08;如 Rectangle、Text&#xff09;构建控件逻辑&#xff0c;通过…

Vue简介,什么是Vue(Vue3)?

什么是Vue&#xff1f; Vue是一款用于构建用户界面的JavaScript框架。 它基于标准HTML、CSS和JavaScript构建&#xff0c;并提供了一套声明式的、组件化的编程模型&#xff0c;帮助你高效地开发用户界面。无论是简单的还是复杂地界面&#xff0c;Vue都可以胜任。 声明式渲染…

从零开始构建Airbyte数据管道:PostgreSQL到BigQuery实战指南

作为数据工程师&#xff0c;ETL&#xff08;Extract, Transform, Load&#xff09;流程是日常工作的核心。然而&#xff0c;构建和维护数据管道往往耗时且复杂。幸运的是&#xff0c;开源工具Airbyte提供了一种更便捷的解决方案——它支持350预构建连接器&#xff0c;允许通过无…

JavaScript的初步学习

目录 JavaScript简介 主要特点 主要用途 JavaScript的基本特性 JavaScript的引入方式 1. 内联方式 (Inline JavaScript) 2. 内部方式 (Internal JavaScript / Embedded JavaScript) 3. 外部方式 (External JavaScript) JavaScript的语法介绍 1.书写语法 2.输出语句 3.…

洛谷P1379 八数码难题【A-star】

P1379 八数码难题 八数码难题首先要进行有解性判定&#xff0c;避免无解情况下盲目搜索浪费时间。 有解性判定 P10454 奇数码问题 题意简述 在一个 n n n \times n nn 的网格中进行&#xff0c;其中 n n n 为奇数&#xff0c; 1 1 1 个空格和 [ 1 , n 2 − 1 ] [1,n^2…

MySQL Buffer Pool 深度解析:从架构设计到性能优化(附详细结构图解)

在 MySQL 数据库的世界里&#xff0c;有一个决定性能上限的"神秘仓库"——Buffer Pool。它就像超市的货架&#xff0c;把最常用的商品&#xff08;数据&#xff09;放在最方便拿取的地方&#xff0c;避免每次都要去仓库&#xff08;磁盘&#xff09;取货。今天我们就…