Rust-Rocket框架笔记
Rocket-Learn-doc
- createTime:20230430
- author:syf20020816@outlook.com
- email:syf20020816@outlook.com
Rocket Addr
地址:https://rocket.rs/v0.5-rc/guide/introduction/
视频地址
What is Rocket
Rocket是Rust的Web框架。如果你愿意,你可以把火箭看作是一个更灵活,更友好支持热插拔,我们更愿意把火箭看作是一种新的东西。Rocket的目标是快速、简单和灵活,同时尽可能提供有保证的安全性。更重要的是,Rocket还致力于成为乐趣,它通过确保您编写尽可能少的代码来完成任务来实现这一点。
Rocket的设计围绕着三个核心理念:
-
安全性、正确性和开发人员体验至关重要。
阻力最小的路径应该会引导您获得最安全,最正确的Web应用程序,尽管安全性和正确性不应该以降低开发人员体验为代价。Rocket易于使用,同时采取了很好的措施来确保您的应用程序是安全和正确的,而无需认知开销。
-
所有请求处理信息都应该是类型化的,并且是独立的。
因为Web和HTTP本身是无类型的(或弦地 类型的,正如一些人所说的那样),这意味着某些东西或某人必须将字符串转换为本地类型。Rocket可以为你做到这一点,而且编程开销为零。更何况,火箭的请求处理是自足的 零全局状态:处理程序是具有常规参数的常规函数。
-
不应强迫作出决定。
模板、序列化、会话以及几乎所有其他组件都是可插拔的可选组件。虽然Rocket对每一个都有官方支持和库,但它们是完全可选和可交换的。
这三个想法决定了Rocket的界面,你会发现它们都嵌入了Rocket的核心功能
QuickStart
下载Rocket-Rust
git clone https://github.com/SergioBenitez/Rocket
cd Rocket/examples/hello
cargo run
运行Rust-Rocket-Hello-错误-端口占用
Configured for debug.
>> address: 127.0.0.1
>> port: 8000
>> workers: 8
>> max blocking threads: 512
>> ident: Rocket
>> IP header: X-Real-IP
>> limits: bytes = 8KiB, data-form = 2MiB, file = 1MiB, form = 32KiB, json = 1MiB, msgpack
= 1MiB, string = 8KiB
>> temp dir: C:\Users\SYF200~1\AppData\Local\Temp\
>> http/2: true
>> keep-alive: 5s
>> tls: disabled
>> shutdown: ctrlc = true, force = true, grace = 2s, mercy = 3s
>> log level: normal
>> cli colors: true
Routes:
>> (hello) GET /?<lang>&<opt..>
>> (wave) GET /wave/<name>/<age>
>> (mir) GET /hello/мир
>> (world) GET /hello/world
Fairings:
>> Shield (liftoff, response, singleton)
>> Compatibility Normalizer (request)
Error: Rocket failed to bind network socket to given address/port.
>> 以一种访问权限不允许的方式做了一个访问套接字的尝试。 (os error 10013)
thread 'main' panicked at 'aborting due to socket bind error', E:\Rust\rocket_learn\Rocket\co
re\lib\src\error.rs:204:17
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
error: process didn't exit successfully: `E:\Rust\rocket_learn\Rocket\examples\target\debug\h
ello.exe` (exit code: 101)
解决
查看端口占用情况
netstat -ano |findstr 8000
添加Rocket.toml配置文件更改Rocket默认启动端口
添加如下内容修改默认端口:
[default]
address = "127.0.0.1"
port = 8080
启动成功
Configured for debug.
>> address: 127.0.0.1
>> port: 8080
>> workers: 8
>> max blocking threads: 512
>> ident: Rocket
>> IP header: X-Real-IP
>> limits: bytes = 8KiB, data-form = 2MiB, file = 1MiB, form = 32KiB, json = 1MiB, msgpack
= 1MiB, string = 8KiB
>> temp dir: C:\Users\SYF200~1\AppData\Local\Temp\
>> http/2: true
>> keep-alive: 5s
>> tls: disabled
>> shutdown: ctrlc = true, force = true, grace = 2s, mercy = 3s
>> log level: normal
>> cli colors: true
Routes:
>> (hello) GET /?<lang>&<opt..>
>> (wave) GET /wave/<name>/<age>
>> (mir) GET /hello/мир
>> (world) GET /hello/world
Fairings:
>> Compatibility Normalizer (request)
>> Shield (liftoff, response, singleton)
Shield:
>> Permissions-Policy: interest-cohort=()
>> X-Frame-Options: SAMEORIGIN
>> X-Content-Type-Options: nosniff
Rocket has launched from http://127.0.0.1:8080
访问:127.0.0.1:8080/?emoji&lang=en
GetStart-Hello world
创建项目
cargo
cargo new hello-rocket
IDEA
添加依赖
[dependencies]
rocket = "=0.5.0-rc.3"
添加Rocket.toml配置文件
[default]
port = 8080
main.rs
#[macro_use] extern crate rocket;
#[get("/index")]
fn index()->&'static str{
"🙂hello world"
}
#[launch]
fn rocket()->_{
rocket::build().mount("/apiV1_4",routes![index])
}
#[get("/")]
:表示设置一个Get请求的方法,在括号中设置请求地址#[launch]
:替代了fn main()
成为Rocket的主入口mount
:方法绑定路由,前面第一个参数是路由前缀
res
E:\Rust\rocket_learn\hello_rocket>cargo run
Compiling hello_rocket v0.1.0 (E:\Rust\rocket_learn\hello_rocket)
Finished dev [unoptimized + debuginfo] target(s) in 2.04s
Running `target\debug\hello_rocket.exe`
Configured for debug.
>> address: 127.0.0.1
>> port: 8080
>> workers: 8
>> max blocking threads: 512
>> ident: Rocket
>> IP header: X-Real-IP
>> limits: bytes = 8KiB, data-form = 2MiB, file = 1MiB, form = 32KiB, json = 1MiB, msgpack
= 1MiB, string = 8KiB
>> temp dir: C:\Users\SYF200~1\AppData\Local\Temp\
>> http/2: true
>> keep-alive: 5s
>> tls: disabled
>> shutdown: ctrlc = true, force = true, grace = 2s, mercy = 3s
>> log level: normal
>> cli colors: true
Routes:
>> (index) GET /apiV1_4/index
Fairings:
>> Shield (liftoff, response, singleton)
Shield:
>> X-Frame-Options: SAMEORIGIN
>> X-Content-Type-Options: nosniff
>> Permissions-Policy: interest-cohort=()
Rocket has launched from http://127.0.0.1:8080
GET /prefix/index text/html:
>> No matching routes for GET /prefix/index text/html.
>> No 404 catcher registered. Using Rocket default.
>> Response succeeded.
GET /apiV1_4/index text/html:
>> Matched: (index) GET /apiV1_4/index
>> Outcome: Success
>> Response succeeded.
Rocket-生命周期
Rocket-请求
方法
以下方法均支持:
`get`、`put`、`post`、`delete`、`head`、`patch`,或`options`
写法:
#[方法类型(路径)]
#[route(方法类型, uri=地址路径)]
例子:
#[get("/")]
#[route(GET , uri = "/")]
动态路径
Restful风格API,使用<>
进行设置
#[get("/hello/<name>")]
fn hello(name: &str) -> String {
format!("Hello, {}!", name)
}
----
#[get("/hello/<name>/<age>/<cool>")]
路径保护
防止路径遍历攻击,必须写在所有路径的最后面
<path..>
例子:
use std::path::{
Path, PathBuf};
use rocket::fs::NamedFile;
#[get("/<file..>")]
async fn files(file: PathBuf) -> Option<NamedFile> {
NamedFile::open(Path::new("static/").join(file)).await.ok()
}
忽略路径
使用占位符_
对路径进行忽略,多路径则使用<_..>
表示对路径进行的忽略操作
#[get("/foo/<_>/bar")]
fn foo_bar() -> &'static str {
"Foo _____ bar!"
}
#[get("/<_..>")]
fn everything() -> &'static str {
"Hey, you're here."
}
转发
路径相同,但是动态路径类型不同,此时会根据类型进行方法的匹配,当然我们可以使用rank提升优先级#[get("/user/<id>",rank=3)]
rank越小优先级越大
// #[macro_use] extern crate rocket;
use rocket::{
get, launch,routes}